# ============================================================
# Nginx Virtual Host — SocialAI Platform
# Domains: ai.3onent.com (frontend) + api.ai.3onent.com (backend)
# ============================================================

# ── HTTP → HTTPS redirect ─────────────────────────────────────
server {
    listen 80;
    listen [::]:80;
    server_name ai.3onent.com api.ai.3onent.com;

    # Let's Encrypt ACME challenge
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

# ============================================================
# Frontend — https://ai.3onent.com
# ============================================================
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ai.3onent.com;

    # ── SSL ──────────────────────────────────────────────────
    ssl_certificate     /etc/letsencrypt/live/ai.3onent.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/ai.3onent.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/ai.3onent.com/chain.pem;

    ssl_session_timeout    1d;
    ssl_session_cache      shared:MozSSL:10m;
    ssl_session_tickets    off;
    ssl_protocols          TLSv1.2 TLSv1.3;
    ssl_ciphers            ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    ssl_stapling           on;
    ssl_stapling_verify    on;

    # ── Security Headers ──────────────────────────────────────
    add_header X-Frame-Options              "SAMEORIGIN"            always;
    add_header X-Content-Type-Options       "nosniff"               always;
    add_header X-XSS-Protection             "1; mode=block"         always;
    add_header Referrer-Policy              "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy           "camera=(), microphone=(), geolocation=()" always;
    add_header Strict-Transport-Security    "max-age=63072000; includeSubDomains; preload" always;
    add_header Content-Security-Policy      "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.paypal.com https://www.sandbox.paypal.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https: blob:; connect-src 'self' https://api.ai.3onent.com wss://api.ai.3onent.com; frame-src https://www.paypal.com https://www.sandbox.paypal.com;" always;

    root /var/www/html/public;
    index index.html;

    # ── Next.js Static Assets ─────────────────────────────────
    location /_next/static/ {
        proxy_pass http://frontend_next;
        proxy_cache         STATIC;
        proxy_cache_valid   200 7d;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        add_header X-Cache-Status $upstream_cache_status;

        add_header Cache-Control "public, max-age=31536000, immutable";
        access_log off;
    }

    location /_next/image {
        proxy_pass http://frontend_next;
        proxy_cache         STATIC;
        proxy_cache_valid   200 24h;
        add_header X-Cache-Status $upstream_cache_status;
    }

    # ── Public static files ───────────────────────────────────
    location ~* \.(ico|svg|png|jpg|jpeg|gif|webp|woff|woff2|ttf|eot)$ {
        proxy_pass http://frontend_next;
        proxy_cache STATIC;
        proxy_cache_valid 200 7d;
        add_header Cache-Control "public, max-age=86400";
        access_log off;
    }

    # ── All other routes → Next.js ────────────────────────────
    location / {
        proxy_pass         http://frontend_next;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade           $http_upgrade;
        proxy_set_header   Connection        'upgrade';
        proxy_set_header   Host              $host;
        proxy_set_header   X-Real-IP         $remote_addr;
        proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;

        proxy_connect_timeout 60s;
        proxy_send_timeout    60s;
        proxy_read_timeout    60s;
    }

    # ── Health check ──────────────────────────────────────────
    location /api/health {
        proxy_pass http://frontend_next;
        access_log off;
    }
}

# ============================================================
# Backend API — https://api.ai.3onent.com
# ============================================================
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name api.ai.3onent.com;

    # ── SSL ──────────────────────────────────────────────────
    ssl_certificate     /etc/letsencrypt/live/ai.3onent.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/ai.3onent.com/privkey.pem;

    ssl_session_timeout  1d;
    ssl_session_cache    shared:MozSSL:10m;
    ssl_session_tickets  off;
    ssl_protocols        TLSv1.2 TLSv1.3;
    ssl_ciphers          ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_stapling         on;
    ssl_stapling_verify  on;

    root /var/www/html/public;
    index index.php;

    # ── Security Headers ──────────────────────────────────────
    add_header X-Frame-Options           "DENY"                  always;
    add_header X-Content-Type-Options    "nosniff"               always;
    add_header X-XSS-Protection          "1; mode=block"         always;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    add_header Access-Control-Allow-Origin  "https://ai.3onent.com" always;
    add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS" always;
    add_header Access-Control-Allow-Headers "Authorization, Content-Type, Accept, X-Requested-With" always;
    add_header Access-Control-Max-Age    "86400" always;

    # ── CORS Preflight ────────────────────────────────────────
    location / {
        if ($request_method = 'OPTIONS') {
            add_header Access-Control-Allow-Origin  "https://ai.3onent.com";
            add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS";
            add_header Access-Control-Allow-Headers "Authorization, Content-Type, Accept, X-Requested-With";
            add_header Access-Control-Max-Age 86400;
            add_header Content-Length 0;
            add_header Content-Type text/plain;
            return 204;
        }

        try_files $uri $uri/ /index.php?$query_string;
    }

    # ── PHP-FPM ───────────────────────────────────────────────
    location ~ \.php$ {
        fastcgi_pass        backend_php;
        fastcgi_index       index.php;
        fastcgi_buffers     16 16k;
        fastcgi_buffer_size 32k;

        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT   $realpath_root;
        include               fastcgi_params;

        fastcgi_connect_timeout 60s;
        fastcgi_send_timeout    180s;
        fastcgi_read_timeout    180s;

        # Hide PHP version
        fastcgi_hide_header X-Powered-By;
    }

    # ── Rate limiting ─────────────────────────────────────────
    location /api/auth/ {
        limit_req zone=auth burst=5 nodelay;
        limit_req_status 429;

        try_files $uri $uri/ /index.php?$query_string;
    }

    location /api/ {
        limit_req zone=api burst=20 nodelay;
        limit_req_status 429;
        limit_conn conn 20;

        try_files $uri $uri/ /index.php?$query_string;
    }

    # ── Media upload endpoint ─────────────────────────────────
    location /api/media/upload {
        limit_req zone=uploads burst=5 nodelay;
        client_max_body_size 110m;

        try_files $uri $uri/ /index.php?$query_string;
    }

    # ── Deny access to sensitive files ────────────────────────
    location ~ /\.(?!well-known) {
        deny all;
    }

    location ~ \.(env|log|htaccess|gitignore|lock)$ {
        deny all;
        return 404;
    }

    # ── Static assets (if served from backend) ────────────────
    location ~* \.(jpg|jpeg|png|gif|ico|svg|webp|woff|woff2|ttf|css|js)$ {
        expires max;
        add_header Cache-Control "public, immutable";
        access_log off;
        try_files $uri =404;
    }

    # ── Health check (no auth needed) ─────────────────────────
    location /health {
        access_log off;
        try_files $uri $uri/ /index.php?$query_string;
    }

    # ── Logs ──────────────────────────────────────────────────
    access_log /var/log/nginx/api.access.log main;
    error_log  /var/log/nginx/api.error.log warn;
}