# ===================================================================
# Nginx-Konfiguration für Meldestelle Web-App
# Static Files + API Proxy zu Gateway
# ===================================================================

# Worker-Prozesse (konfigurierbar über NGINX_WORKER_PROCESSES)
worker_processes auto;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Logging
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    # Performance Optimizations
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    # Gzip Kompression für bessere Performance
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/xml+rss
        application/json
        application/wasm;

    # Upstream für API Gateway
    upstream api-gateway {
        server api-gateway:8081;
    }

    # Server-Block für Web-App
    server {
        listen 4000;
        server_name localhost;
        root /usr/share/nginx/html;
        index index.html;

        # Serve static files (Kotlin/JS compiled files)
        location / {
            try_files $uri $uri/ /index.html;

            # Cache-Headers für statische Assets
            location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
                expires 1y;
                add_header Cache-Control "public, immutable";
            }

            # WASM Files mit korrektem MIME-Type
            location ~* \.wasm$ {
                add_header Content-Type application/wasm;
                expires 1y;
                add_header Cache-Control "public, immutable";
            }
        }

        # Proxy API calls zu Gateway
        location /api/ {
            proxy_pass http://api-gateway;
            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;

            # CORS Headers für API-Calls
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
            add_header Access-Control-Allow-Headers "Content-Type, Authorization";

            # Handle preflight requests
            if ($request_method = 'OPTIONS') {
                return 204;
            }
        }

        # Health-Check Endpoint
        location /health {
            access_log off;
            return 200 "healthy\n";
            add_header Content-Type text/plain;
        }
    }
}
