#!/bin/bash
# ============================================================
# 03_nginx.sh
# Sets up Nginx config for me.goteku.com
# Run as root AFTER 02_deploy.sh
# ============================================================
set -e

DOMAIN="me.goteku.com"
DEPLOY_DIR="/var/www/html/me.goteku.com"

echo "=== Writing Nginx config ==="
cat > /etc/nginx/sites-available/${DOMAIN} <<'NGINXCONF'
server {
    listen 80;
    server_name me.goteku.com;

    # Frontend — serve React build
    root /var/www/html/me.goteku.com/frontend/dist;
    index index.html;

    # React Router — always serve index.html for unknown paths
    location / {
        try_files $uri $uri/ /index.html;
    }

    # API — proxy to FastAPI backend
    location /api/ {
        proxy_pass http://127.0.0.1:8002;
        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 60s;
    }

    # Larger uploads if needed
    client_max_body_size 10M;
}
NGINXCONF

echo "=== Enabling site ==="
ln -sf /etc/nginx/sites-available/${DOMAIN} /etc/nginx/sites-enabled/${DOMAIN}

# Remove default site if still enabled
rm -f /etc/nginx/sites-enabled/default

echo "=== Testing Nginx config ==="
nginx -t

echo "=== Reloading Nginx ==="
systemctl reload nginx

echo "✅ Nginx configured for ${DOMAIN}"
echo "   Next: run 04_ssl.sh to enable HTTPS"
