user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout 65;
    server_tokens off;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript application/json
               application/javascript application/xml+rss application/atom+xml
               image/svg+xml;

    # Client body size limit (50MB for file uploads)
    client_max_body_size 50m;

    # URL length limit
    large_client_header_buffers 4 8k;

    # Rate limiting zones
    limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=auth:10m    rate=1r/s;
    limit_req_zone $binary_remote_addr zone=upload:10m  rate=5r/s;

    # SSL session cache
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;

    # HTTP → HTTPS redirect
    server {
        listen 80;
        server_name _;
        return 301 https://$host$request_uri;
    }

    server {
        listen 443 ssl;
        http2 on;
        server_name _;

        # TLS configuration — TLS 1.2 minimum, TLS 1.3 preferred
        ssl_certificate     /etc/nginx/certs/fullchain.pem;
        ssl_certificate_key /etc/nginx/certs/privkey.pem;
        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 (per SECURITY-GUIDELINES.md § 6.2)
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-Frame-Options "DENY" always;
        add_header X-XSS-Protection "0" always;
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;
        add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self' wss:; frame-ancestors 'none';" always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;

        # CORS headers
        set $cors_origin "";
        if ($http_origin ~* "^https://(crm\.portnimara\.com|portnimara\.com)$") {
            set $cors_origin $http_origin;
        }
        add_header Access-Control-Allow-Origin $cors_origin always;
        add_header Access-Control-Allow-Credentials "true" always;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS" always;
        add_header Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With" always;
        add_header Access-Control-Max-Age "3600" always;

        # Preflight
        if ($request_method = OPTIONS) {
            return 204;
        }

        # Auth endpoints — strict rate limit (1r/s → ~5 req/min burst)
        location ~ ^/api/auth/ {
            limit_req zone=auth burst=5 nodelay;
            limit_req_status 429;
            proxy_pass http://crm-app:3000;
            include /etc/nginx/conf.d/proxy_params.conf;
        }

        # File upload endpoints — dedicated rate limit
        location ~ ^/api/v1/files {
            limit_req zone=upload burst=10 nodelay;
            limit_req_status 429;
            client_max_body_size 50m;
            proxy_pass http://crm-app:3000;
            proxy_request_buffering off;
            include /etc/nginx/conf.d/proxy_params.conf;
        }

        # WebSocket upgrade for Socket.io
        location /socket.io/ {
            limit_req zone=general burst=20 nodelay;
            proxy_pass http://crm-app:3000;
            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_read_timeout 86400s;
            proxy_send_timeout 86400s;
        }

        # All other traffic — general rate limit
        location / {
            limit_req zone=general burst=20 nodelay;
            limit_req_status 429;
            proxy_pass http://crm-app:3000;
            include /etc/nginx/conf.d/proxy_params.conf;
        }
    }
}
