# Map for proper WebSocket upgrade handling on the proxied locations below.
# Hardcoding `proxy_set_header Connection "upgrade"` puts nginx into tunnel-
# mode for every request, which has caused subtle bugs in the past. This
# variant only sets Connection: upgrade when the client actually requested
# an Upgrade (real WebSocket); otherwise it's "close".
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

# Forward the outer X-Forwarded-Proto when present; fall back to $scheme.
# THIS IS WHY LOGIN WAS LOOPING: web-ui listens on port 80 inside the
# container, so $scheme is always "http". With `proxy_set_header
# X-Forwarded-Proto $scheme;`, mam-api saw http, decided req.secure=false,
# and (because cookie.secure=true in production) silently refused to emit
# the Set-Cookie at all. NPM correctly sends X-Forwarded-Proto: https on
# the outer request — we just have to pass it through to mam-api.
map $http_x_forwarded_proto $proxied_x_forwarded_proto {
    default $http_x_forwarded_proto;
    ''      $scheme;
}

server {
    listen 80;
    server_name _;

    # Docker embedded DNS — defers upstream resolution to request time
    # This prevents nginx crashing at startup if sibling containers aren't
    # ready yet (which happens on the first `docker compose up`).
    resolver 127.0.0.11 valid=10s ipv6=off;

    # Allow unlimited client upload size
    client_max_body_size 0;

    # Gzip compression
    gzip on;
    gzip_types text/plain text/css text/javascript application/javascript application/json;
    gzip_min_length 1000;

    # Root location - serve static files
    root /usr/share/nginx/html;

    # Fonts, icons, images: rarely change, safe to cache aggressively.
    location ~* \.(png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # CSS / JS — must revalidate so a redeploy is picked up immediately.
    # The index.html links these without a version query string, so without
    # this rule a stale stylesheet/script sits in the browser cache forever
    # (which produced the unstyled calendar that triggered this fix).
    location ~* \.(css|js)$ {
        expires -1;
        add_header Cache-Control "no-cache, must-revalidate";
    }

    # HTML files - no cache
    location ~* \.html?$ {
        expires -1;
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }

    # Live HLS — served from /live (bind-mounted capture live volume).
    # no-store (not just no-cache): with "no-cache" the browser still caches the
    # playlist and serves a STALE copy to hls.js's reloads, so hls.js sees the
    # live playlist as never advancing ("MISSED" forever) and never plays — the
    # monitor stays black. no-store forbids caching entirely so every reload
    # fetches the fresh live edge. Segments are short-lived; not caching them is
    # fine for a live preview.
    location /live/ {
        alias /live/;
        types { application/vnd.apple.mpegurl m3u8; video/mp2t ts; }
        add_header Cache-Control "no-store, no-cache, must-revalidate" always;
        add_header Pragma "no-cache" always;
        add_header Access-Control-Allow-Origin * always;
    }

    # Playout HLS preview — CasparCG sidecar writes to the media volume under
    # /media/live/<channel_id>/. This is a separate volume from /live/ (capture).
    location /media/live/ {
        alias /media/live/;
        types { application/vnd.apple.mpegurl m3u8; video/mp2t ts; }
        add_header Cache-Control "no-store, no-cache, must-revalidate" always;
        add_header Pragma "no-cache" always;
        add_header Access-Control-Allow-Origin * always;
    }

    # API proxy - forward to mam-api service
    location /api/ {
        set $api_upstream http://mam-api:3000;
        client_max_body_size 0;
        proxy_pass $api_upstream;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $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 $proxied_x_forwarded_proto;
        # Preserve Content-Type so multer receives the full multipart boundary (#74)
        proxy_set_header Content-Type $content_type;
        proxy_buffering off;
        proxy_request_buffering off;
        proxy_connect_timeout 300;
        proxy_send_timeout 300;
        proxy_read_timeout 300;
    }

    # Capture proxy - forward to capture service
    location /capture/ {
        set $capture_upstream http://capture:3001;
        proxy_pass $capture_upstream;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $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 $proxied_x_forwarded_proto;
        proxy_buffering off;
        proxy_request_buffering off;
    }

    # Premiere panel downloads — served as binary attachments
    location /downloads/ {
        add_header Cache-Control "public, max-age=86400";
        add_header Content-Disposition 'attachment';
    }

    # SPA fallback - try to serve file, else route to the React shell.
    location / {
        try_files $uri $uri/ /index.html;
        expires -1;
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }

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