events {
    worker_connections 1024;
}

http {
    upstream frontend {
        server localhost:5173;
    }
    
    upstream api {
        server localhost:3000;
    }

    server {
        listen 80;
        server_name localhost;
        
        resolver 127.0.0.11 valid=30s;

        location /api {
            proxy_pass http://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;
        }

        # Port forwarding - matches /port/8080, /port/3001, etc.
        # Routes to localhost ports (containers running in Docker-in-Docker)
        location ~ ^/port/(\d+)(/.*)?$ {
            set $port $1;
            set $path $2;
            set $target localhost:$port;
            proxy_pass http://$target$path;
            proxy_set_header Host localhost:$port;
            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;
            
            # Pass through authentication headers for HTTP Basic Auth
            proxy_pass_header Authorization;
            proxy_set_header Authorization $http_authorization;
            
            # WebSocket support for development servers
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            
            # Additional headers for better compatibility
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_buffering off;
            
            # Handle authentication responses properly
            proxy_intercept_errors off;
        }

        location / {
            proxy_pass http://frontend;
            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_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }
}