server {
    listen 80;
    server_name api.${DOMAIN};
    add_header X-Frame-Options "SAMEORIGIN" always;

    # Media API endpoints (must come BEFORE / for longest prefix match)
    # Uses variable proxy_pass for runtime DNS resolution after container restarts
    location /media/ {
        limit_req zone=api_global burst=60 nodelay;
        set $upstream_media http://changemaker-media-api:4100;
        rewrite ^/media/(.*) /api/$1 break;
        proxy_pass $upstream_media;
        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;

        # Large upload support
        client_max_body_size 10G;
        proxy_read_timeout 3600s;
        proxy_connect_timeout 75s;
        proxy_request_buffering off;

        # WebSocket support
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # Auth endpoints — stricter rate limit to prevent credential stuffing
    location /api/auth/ {
        limit_req zone=api_auth burst=10 nodelay;
        set $upstream_api http://changemaker-v2-api:4000;
        proxy_pass $upstream_api;
        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 300s;
        proxy_connect_timeout 75s;
    }

    # Main API (Express)
    location / {
        limit_req zone=api_global burst=60 nodelay;
        set $upstream_api http://changemaker-v2-api:4000;
        proxy_pass $upstream_api;
        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 300s;
        proxy_connect_timeout 75s;
    }
}
