# ISO8601 시간을 "YYYY-MM-DD HH:mm:ss" 형식으로 변환
map $time_iso8601 $time_custom {
    "~^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})" "$1-$2-$3 $4:$5:$6";
}

# Go slog 포맷과 맞춘 JSON 액세스 로그
log_format json_combined escape=json
    '{'
    '"time":"$time_custom",'
    '"level":"INFO",'
    '"msg":"http_access",'
    '"svc":"baron-userfront",'
    '"status":$status,'
    '"method":"$request_method",'
    '"path":"$request_uri",'
    '"latency":"${request_time}s",'
    '"ip":"$remote_addr",'
    '"forwarded_for":"$http_x_forwarded_for",'
    '"user_agent":"$http_user_agent"'
    '}';

server {
    listen 5000;
    include /etc/nginx/mime.types;
    types {
        application/javascript mjs;
        application/wasm wasm;
    }
    
    error_log /dev/stderr warn;
    access_log /var/log/nginx/access.log json_combined;

    # --- Backend API Proxy ---
    location /api {
        proxy_pass http://backend:{{BACKEND_PORT}};
        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;
    }

    # --- UserFront Static Files ---
    
    location ~* \.(js|css|html|json|mjs|wasm)$ {
        root /usr/share/nginx/html;
        add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
        try_files $uri =404;
    }

    location ~* \.mjs$ {
        root /usr/share/nginx/html;
        default_type application/javascript;
        add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
        try_files $uri =404;
    }

    # dart2wasm 바이너리 MIME 명시
    location ~* \.wasm$ {
        root /usr/share/nginx/html;
        default_type application/wasm;
        add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
        try_files $uri =404;
    }

    location / {
        root /usr/share/nginx/html;
        index index.html;
        add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
        try_files $uri $uri/ /index.html;
    }
}
