# the events block is required
events {}

http {
    # include the default mime.types to map file extensions to MIME types
    include /etc/nginx/mime.types;

    # Set max request body size to 100MB (adjust as needed)
    client_max_body_size 1000M;
    
    proxy_buffer_size 128k;
    proxy_buffers 4 256k;
    proxy_busy_buffers_size 256k;
    large_client_header_buffers 8 32k;

    server {
        listen ${BOOKLORE_PORT};
        listen [::]:${BOOKLORE_PORT};

        # Set the root directory for the server (Angular app)
        root /usr/share/nginx/html;

        # Set the default index file for the server
        index index.html;

        # Serve Angular UI
        location / {
            try_files $uri $uri/ /index.html;  # Fallback to index.html for Angular routing

            location ~* \.mjs$ {
                # target only *.mjs files
                # now we can safely override types since we are only
                # targeting a single file extension.
                types {
                    text/javascript mjs;
                }
            }
        }

        # Proxy API requests that start with /api/ to the backend
        location /api/ {
            proxy_pass http://localhost:8080;
            proxy_set_header X-Forwarded-Port $server_port;
            proxy_set_header X-Forwarded-Host $host;
        }

        # Proxy WebSocket requests (ws://) to the backend
        location /ws {
            proxy_pass http://localhost:8080/ws;  # Backend WebSocket endpoint
            proxy_http_version 1.1;  # Ensure HTTP 1.1 is used for WebSocket connection
            proxy_set_header Upgrade $http_upgrade;  # Pass the upgrade header
            proxy_set_header Connection 'upgrade';  # Pass the connection header
            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;
        }
    }
}