# Nginx configuration for Bakery IA Frontend
# This file is used inside the container at /etc/nginx/conf.d/default.conf

server {
    listen 3000;
    server_name localhost;
    root /usr/share/nginx/html;
    index index.html;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://fonts.googleapis.com https://js.stripe.com; script-src-elem 'self' 'unsafe-inline' https://js.stripe.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self' http://localhost http://localhost:8000 http://localhost:8001 http://localhost:8006 ws: wss:; frame-src https://js.stripe.com;" always;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml;

    # Note: API routing is handled by ingress, not by this nginx
    # The frontend makes requests to /api which are routed by the ingress controller

    # Static assets with aggressive caching (including source maps for debugging)
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|map)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        add_header Vary Accept-Encoding;
        access_log off;
        try_files $uri =404;
    }

    # Special handling for PWA assets
    location ~* \.(webmanifest|manifest\.json)$ {
        expires 1d;
        add_header Cache-Control "public";
        add_header Content-Type application/manifest+json;
    }

    location = /sw.js {
        expires 1d;
        add_header Cache-Control "public";
        add_header Content-Type application/javascript;
    }

    # Main location block for SPA routing
    location / {
        try_files $uri $uri/ @fallback;
    }

    # Fallback for SPA routing - serve index.html
    location @fallback {
        rewrite ^.*$ /index.html last;
    }

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

    # Deny access to hidden files
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

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