#!/bin/bash

set -e

echo "🚀 Neon Database Setup Script"
echo ""

# Source OS helper
source "$(dirname "$0")/../utils/os-helper.sh"

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${YELLOW}This script helps you set up Neon database for all environments.${NC}"
echo ""

# EN: Check if .env.local exists
# VI: Kiểm tra xem .env.local có tồn tại không
ENV_LOCAL="deployments/local/.env.local"
if [ ! -f "$ENV_LOCAL" ]; then
    echo "📝 Creating $ENV_LOCAL from example..."
    cp deployments/local/env.local.example "$ENV_LOCAL"
    echo -e "${GREEN}✅ Created $ENV_LOCAL${NC}"
    echo ""
fi

echo "📋 Setup Steps:"
echo ""
echo "1. Go to https://console.neon.tech"
echo "2. Create a project (or use existing): goodgo-platform"
echo "3. Create branches:"
echo "   - staging (from main)"
echo "   - production (from main)"
echo ""
echo "4. Get connection strings for each branch from Neon Console"
echo "   Format: postgresql://user:password@ep-xxx.region.neon.tech/dbname?sslmode=require&pgbouncer=true"
echo ""

read -p "Enter development DATABASE_URL (main branch): " dev_url
if [ -n "$dev_url" ]; then
    # EN: Update .env.local with new URL
    # VI: Cập nhật .env.local với URL mới
    if grep -q "DATABASE_URL=" "$ENV_LOCAL"; then
        run_sed "s|DATABASE_URL=.*|DATABASE_URL=$dev_url|" "$ENV_LOCAL"
    else
        echo "DATABASE_URL=$dev_url" >> "$ENV_LOCAL"
    fi
    echo -e "${GREEN}✅ Updated $ENV_LOCAL${NC}"
fi

echo ""
echo "📝 Next Steps:"
echo ""
echo "1. Add to GitHub Secrets (for CI/CD):"
echo "   - NEON_DATABASE_URL_STAGING"
echo "   - NEON_DATABASE_URL_PRODUCTION"
echo "   - NEON_DATABASE_URL_TEST (optional, for CI tests)"
echo ""
echo "2. Create Kubernetes secrets for staging/production:"
echo "   See: deployments/staging/kubernetes/secrets.yaml.example"
echo "   See: deployments/production/kubernetes/secrets.yaml.example"
echo ""
echo "3. Run initial migration:"
echo "   ./scripts/db/migrate.sh iam-service dev"
echo ""
echo "4. Seed database (optional):"
echo "   ./scripts/db/seed.sh iam-service"
echo ""
echo -e "${GREEN}✅ Setup instructions complete!${NC}"
echo ""
echo "For more details, see: infra/databases/neon/README.md"
