# Domain-wide login wall for the POC host (poc.digt.ch / stage.poc.digt.ch).
#
# Every request is authorised by the hub's /api/authz before nginx proxies it:
#   200 → allowed        401 → not logged in (→ redirect to the hub /login)
#   403 → logged in, but not allowed this app
#
# The hub (Next standalone) serves "/"; each POC serves "/<slug>". The hub's
# /api/authz validates the session cookie and checks the requested slug against the
# user's allowlist — so the POC apps need NO auth code of their own.
#
# This is an EXAMPLE to adapt on the server; not applied automatically.

upstream poc_hub { server 127.0.0.1:3000; }
# upstream invoice_ocr { server 127.0.0.1:3010; }   # one per POC

server {
  server_name poc.digt.ch;          # also: stage.poc.digt.ch
  listen 443 ssl;                    # ... your TLS config ...

  # --- the auth subrequest (internal) -------------------------------------
  location = /__authz {
    internal;
    proxy_pass            http://poc_hub/api/authz;
    proxy_pass_request_body off;
    proxy_set_header      Content-Length "";
    proxy_set_header      X-Original-URI $request_uri;   # what we're authorising
    # the original Cookie header is forwarded automatically
  }

  # 401 → bounce to the hub login, remembering where they were headed.
  error_page 401 = @login;
  location @login { return 302 /login?from=$request_uri; }
  # 403 → logged in but not entitled to this app.
  error_page 403 = @forbidden;
  location @forbidden { default_type text/plain; return 403 "No access to this app."; }

  # --- the hub (and /login, /_next, /api/auth, /api/authz — treated as public
  #     by /api/authz, so the login flow is reachable) ------------------------
  location / {
    auth_request /__authz;
    proxy_pass            http://poc_hub;
    proxy_set_header      Host $host;
    proxy_set_header      X-Forwarded-Proto $scheme;
    proxy_set_header      X-Forwarded-Host $host;
  }

  # --- one block per POC app (gated by the same auth_request) ---------------
  # location /invoice-ocr/ {
  #   auth_request /__authz;
  #   proxy_pass        http://invoice_ocr/;   # the POC built with BASE_PATH=/invoice-ocr
  #   proxy_set_header  Host $host;
  #   proxy_set_header  X-Forwarded-Proto $scheme;
  # }
}
