server {
    listen 80;
    server_name _;
    root /usr/share/nginx/html;
    index index.html;

    resolver 127.0.0.11 valid=30s;

    # Return Authentik user identity (email injected by Traefik forward-auth)
    location = /auth/whoami {
        default_type application/json;
        return 200 '{"email":"$http_x_authentik_email","username":"$http_x_authentik_username","groups":"$http_x_authentik_groups"}';
    }

    # ERPNext API proxy — token injected SERVER-SIDE at deploy (never in the JS bundle, never committed).
    # deploy.sh fills the placeholder below from the server's /opt/targo-hub/.env ERP_TOKEN
    # (the dedicated service account hub-service@targo.ca — NOT Administrator). Rotate = re-run deploy.sh.
    location /api/ {
        proxy_pass https://erp.gigafibre.ca;
        proxy_ssl_verify off;
        proxy_set_header Host erp.gigafibre.ca;
        proxy_set_header Authorization "token __ERP_API_TOKEN__";
        proxy_set_header X-Authentik-Email $http_x_authentik_email;
        proxy_set_header X-Authentik-Username $http_x_authentik_username;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
    }

    # Ollama Vision API proxy (kept for legacy vision paths; primary OCR goes through the hub)
    location /ollama/ {
        set $ollama_upstream http://ollama:11434;
        proxy_pass $ollama_upstream/;
        proxy_set_header Host $host;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
        client_max_body_size 20m;
    }

    # targo-hub proxy — service token injected SERVER-SIDE at deploy (never bundled/committed).
    # deploy.sh fills the placeholder below from the server's /opt/targo-hub/.env HUB_SERVICE_TOKEN.
    location /hub/ {
        proxy_pass https://msg.gigafibre.ca/;
        proxy_ssl_verify off;
        proxy_set_header Host msg.gigafibre.ca;
        proxy_set_header Authorization "Bearer __HUB_TOKEN__";
        proxy_set_header X-Authentik-Email $http_x_authentik_email;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_buffering off;
        proxy_read_timeout 3600s;
        client_max_body_size 8m; # pièces jointes événement (image/PDF base64, ~5.5m pour 4m de binaire)
    }

    # SPA fallback — all routes serve index.html
    location / {
        try_files $uri $uri/ /index.html;
    }

    # No cache for index.html and service worker
    location = /index.html {
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }
    location = /sw.js {
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }

    # Cache static assets (30 days, immutable)
    location /assets/ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
