# /etc/nginx/sites-available/chatgpt-chatbot
#
# Terminates TLS and proxies to the Node process on localhost. Node itself
# should never be exposed to the internet directly — bind it to 127.0.0.1 and
# let the EC2 security group allow only 80/443 from outside.

server {
    listen 80;
    server_name chat.yourdomain.com;

    # certbot --nginx rewrites this block to redirect to 443.
    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl http2;
    server_name chat.yourdomain.com;

    ssl_certificate     /etc/letsencrypt/live/chat.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/chat.yourdomain.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options DENY always;

    # A single reply with web search can take a while; the default 60s read
    # timeout would cut long streams off mid-answer.
    proxy_read_timeout 180s;
    proxy_send_timeout 180s;

    # Must exceed MAX_PDF_MB, or nginx rejects an upload with its own HTML 413
    # before Node ever sees it — and the client gets no JSON error to show.
    # Leave headroom: multipart framing adds a little to the raw file size.
    client_max_body_size 12m;

    # A 10-page PDF summary regularly takes 30-60s of upstream work.
    proxy_request_buffering off;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;

        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;

        # Required for SSE: without these, nginx buffers the whole response and
        # the stream arrives in one lump at the end.
        proxy_buffering off;
        proxy_cache off;
        proxy_set_header Connection "";
    }
}
