upstream frontend {
    server frontend:5173;
}

# ── HTTP → HTTPS Redirect ──
server {
    listen 80 default_server;
    server_name dociva.io www.dociva.io;

    # Let's Encrypt challenge
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    # Redirect all other traffic to HTTPS
    location / {
        return 301 https://$host$request_uri;
    }
}

# ── HTTPS Server ──
server {
    listen 443 ssl;
    server_name dociva.io www.dociva.io;

    # SSL Certificate
    ssl_certificate /etc/letsencrypt/live/dociva.io/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/dociva.io/privkey.pem;

    # SSL Configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    client_max_body_size 100M;
    resolver 127.0.0.11 valid=30s ipv6=off;
    set $backend_upstream backend:5000;

    # API requests → Flask backend
    location /api/ {
        proxy_pass http://$backend_upstream;
        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;

        # Timeout for large file uploads
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
        proxy_connect_timeout 60s;
    }

    # Frontend (Vite dev server)
    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 Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # Health check
    location /health {
        proxy_pass http://$backend_upstream/api/health;
    }
}
