server {
    listen 80;
    server_name db.rebreak.org;
    return 301 https://db.rebreak.org$request_uri;
}

server {
    listen 443 ssl;
    server_name db.rebreak.org;

    ssl_certificate     /etc/letsencrypt/live/db.rebreak.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/db.rebreak.org/privkey.pem;

    location = / {
        default_type application/json;
        return 200 '{"status":"ok"}';
    }

    # Direct WebSocket proxy to Supabase Realtime (bypasses Kong)
    location /realtime/v1/ {
        rewrite ^/realtime/v1/(.*)$ /socket/$1 break;
        proxy_pass http://172.19.0.27:4000;
        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_read_timeout 3600s;
        proxy_send_timeout 3600s;
    }

    location / {
        client_max_body_size 50M;

        if ($request_method = OPTIONS) {
            add_header Access-Control-Allow-Origin      $http_origin always;
            add_header Access-Control-Allow-Credentials "true" always;
            add_header Access-Control-Allow-Methods     "GET, POST, PUT, DELETE, PATCH, OPTIONS" always;
            add_header Access-Control-Allow-Headers     "Authorization, apikey, x-client-info, content-type, range, x-upsert, accept, prefer, x-supabase-api-version, accept-profile, content-profile" always;
            add_header Access-Control-Max-Age           3600 always;
            return 204;
        }

        proxy_pass http://127.0.0.1:54321;
        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_hide_header Access-Control-Allow-Origin;
        proxy_hide_header Access-Control-Allow-Credentials;
        proxy_hide_header Access-Control-Allow-Methods;
        proxy_hide_header Access-Control-Allow-Headers;
        proxy_hide_header Access-Control-Expose-Headers;

        add_header Access-Control-Allow-Origin      $http_origin always;
        add_header Access-Control-Allow-Credentials "true" always;
    }
}
