#!/bin/bash
# scripts/setup-nginx.sh - Настройка nginx для CatLink

set -e

echo "⚙️ Настройка nginx конфигурации..."

# Создание конфигурации nginx (HTTP-only для начала)
sudo tee /etc/nginx/sites-available/links > /dev/null << 'EOF'
server {
    listen 80;
    server_name links.shareon.kr sharon.kr localhost;

    # Proxy to frontend (Next.js)
    location / {
        proxy_pass http://localhost:3000;
        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_cache_bypass $http_upgrade;
        proxy_read_timeout 86400;
    }

    # Proxy API requests to backend (Django)
    location /api/ {
        proxy_pass http://localhost:8000;
        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 admin requests to backend (Django)
    location /admin/ {
        proxy_pass http://localhost:8000;
        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;
    }

    # Serve static files from Django
    location /static/ {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Serve media files from Django
    location /media/ {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        expires 1y;
        add_header Cache-Control "public";
    }

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

echo "🔗 Активация конфигурации nginx..."
sudo mkdir -p /var/www/html
sudo ln -sf /etc/nginx/sites-available/links /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default

echo "🧪 Проверка конфигурации nginx..."
sudo nginx -t

echo "🔄 Перезапуск nginx..."
sudo systemctl restart nginx
sudo systemctl enable nginx

echo "✅ nginx настройка завершена"
echo ""
echo "📝 Для настройки SSL выполните:"
echo "   make ssl-cert"
echo ""
echo "🌐 Временно доступно по HTTP:"
echo "   http://links.shareon.kr (если DNS настроен)"
echo "   http://localhost (локально)"