events {
    worker_connections 1024;
}

http {
    upstream frontend {
        server frontend:3000;
    }

    upstream backend {
        server backend:8080;
    }

    server {
        listen 80;
        client_max_body_size 4096M;  # 4GB for large backup uploads

        # Frontend routes
        location / {
            proxy_pass http://frontend;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            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;
            proxy_cache_bypass $http_upgrade;
        }

        # Scraping routes - completely separate from /api/ to avoid conflicts
        location /scrape/ {
            proxy_pass http://frontend/scrape/;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            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;
            proxy_cache_bypass $http_upgrade;
            # Extended timeouts for bulk scraping operations
            proxy_connect_timeout 900s;
            proxy_send_timeout 900s;
            proxy_read_timeout 900s;
        }

        # Backend API routes (fallback for all other /api/ routes)
        location /api/ {
            proxy_pass http://backend/api/;
            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;
            proxy_connect_timeout 900s;
            proxy_send_timeout 900s;
            proxy_read_timeout 900s;
            # Large upload settings (4GB for backups)
            client_max_body_size 4096M;
            proxy_request_buffering off;
            proxy_max_temp_file_size 0;
        }

        # Static image serving
        location /images/ {
            alias /app/images/;
            expires 1y;
            add_header Cache-Control "public, immutable";
        }

        # Typesense admin interface
        location /typesense/ {
            proxy_pass http://typesense:8108/;
            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;
            proxy_set_header X-Typesense-API-Key $http_x_typesense_api_key;
        }
    }
}