# HTTPS Server Block (main)
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name flyer-crawler-test.projectium.com;

    # SSL Configuration (managed by Certbot)
    ssl_certificate /etc/letsencrypt/live/flyer-crawler-test.projectium.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/flyer-crawler-test.projectium.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # Allow large file uploads (e.g., for flyers)
    client_max_body_size 100M;

    # Root directory for built application files
    root /var/www/flyer-crawler-test.projectium.com;
    index index.html;

    # Deny access to all dotfiles
    location ~ /\. {
        deny all;
        return 404;
    }

    # Coverage report (must come before generic location /)
    location /coverage/ {
        try_files $uri $uri/ =404;
    }

    # SPA fallback for React Router
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Reverse proxy for backend API
    location /api/ {
        proxy_connect_timeout 300s;
        proxy_send_timeout    300s;
        proxy_read_timeout    300s;

        proxy_pass http://localhost:3002;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    # Correct MIME type for .mjs files
    location ~ \.mjs$ {
        include /etc/nginx/mime.types;
        default_type application/javascript;
    }

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
}

# HTTP to HTTPS Redirect
server {
    listen 80;
    listen [::]:80;
    server_name flyer-crawler-test.projectium.com;

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