#!/bin/bash
# =============================================================================
# deploy-postgres.sh — One-time deployment script for Postgres migration
# =============================================================================
# Run this ONCE on a fresh server after pulling the feature/multi-tenancy code.
# Prerequisites: Docker installed, Node.js 18+, npm
#
# What this does:
#   1. Starts the Postgres container (docker compose)
#   2. Waits for Postgres to be ready
#   3. Runs the schema DDL
#   4. Installs npm dependencies (adds 'pg' package)
#   5. Runs the data migration script (SQLite → Postgres)
#   6. Rebuilds the frontend
#   7. Prints next steps
#
# Usage:
#   chmod +x scripts/deploy-postgres.sh
#   ./scripts/deploy-postgres.sh
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_DIR"

echo ""
echo "╔════════════════════════════════════════════════════════╗"
echo "║   CVE Dashboard — Postgres Deployment Script          ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""

# Check prerequisites
command -v docker >/dev/null 2>&1 || { echo "ERROR: Docker is not installed. Install with: apt install -y docker.io"; exit 1; }
command -v node >/dev/null 2>&1 || { echo "ERROR: Node.js is not installed."; exit 1; }
command -v psql >/dev/null 2>&1 || { echo "WARNING: psql not found. Installing postgresql-client..."; apt install -y postgresql-client >/dev/null 2>&1 || true; }

# Check if .env has DATABASE_URL
if ! grep -q "DATABASE_URL" backend/.env 2>/dev/null; then
    echo "Adding DATABASE_URL to backend/.env..."
    echo "" >> backend/.env
    echo "# PostgreSQL (Docker container steam-postgres on port 5433)" >> backend/.env
    echo "DATABASE_URL=postgresql://steam:sV4xmC9xAUCFop0ypxMVS056QgPqGrX@localhost:5433/cve_dashboard" >> backend/.env
    echo "✓ DATABASE_URL added to .env"
else
    echo "✓ DATABASE_URL already in .env"
fi

# Step 1: Start Postgres container
echo ""
echo "── Step 1: Starting Postgres container ──"
if docker ps --format '{{.Names}}' | grep -q steam-postgres; then
    echo "✓ steam-postgres container already running"
else
    docker compose up -d
    echo "✓ Container started"
fi

# Step 2: Wait for Postgres to be ready
echo ""
echo "── Step 2: Waiting for Postgres to be ready ──"
for i in $(seq 1 30); do
    if PGPASSWORD=sV4xmC9xAUCFop0ypxMVS056QgPqGrX psql -h localhost -p 5433 -U steam -d cve_dashboard -c "SELECT 1" >/dev/null 2>&1; then
        echo "✓ Postgres is ready"
        break
    fi
    if [ $i -eq 30 ]; then
        echo "ERROR: Postgres did not become ready in 30 seconds"
        exit 1
    fi
    sleep 1
done

# Step 3: Run schema
echo ""
echo "── Step 3: Creating schema ──"
PGPASSWORD=sV4xmC9xAUCFop0ypxMVS056QgPqGrX psql -h localhost -p 5433 -U steam -d cve_dashboard -f backend/db-schema.sql >/dev/null 2>&1
echo "✓ Schema created"

# Step 4: Install dependencies
echo ""
echo "── Step 4: Installing npm dependencies ──"
cd backend && npm install --production >/dev/null 2>&1 && cd ..
echo "✓ Dependencies installed"

# Step 5: Run data migration
echo ""
echo "── Step 5: Running data migration (SQLite → Postgres) ──"
if [ -f backend/cve_database.db ]; then
    if ! node backend/scripts/migrate-to-postgres.js; then
        echo ""
        echo "⚠ Migration failed — resetting database and retrying..."
        PGPASSWORD=sV4xmC9xAUCFop0ypxMVS056QgPqGrX psql -h localhost -p 5433 -U steam -d cve_dashboard -c "
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
" >/dev/null 2>&1
        echo "✓ Schema reset"
        node backend/scripts/migrate-to-postgres.js
    fi
else
    echo "⚠ No SQLite database found — skipping migration (fresh install)"
fi

# Step 6: Build frontend
echo ""
echo "── Step 6: Building frontend ──"
cd frontend && npm install >/dev/null 2>&1 && npm run build >/dev/null 2>&1 && cd ..
echo "✓ Frontend built"

# Done
echo ""
echo "╔════════════════════════════════════════════════════════╗"
echo "║   Deployment complete!                                 ║"
echo "╚════════════════════════════════════════════════════════╝"
echo ""
echo "Next steps:"
echo "  1. Stop the old backend:  kill \$(lsof -t -i:3001)"
echo "  2. Start the new backend: node backend/server.js"
echo "  3. Verify: curl http://localhost:3001/api/auth/me"
echo ""
echo "Rollback (if needed):"
echo "  1. Stop the new backend"
echo "  2. Remove DATABASE_URL from backend/.env"
echo "  3. git checkout master~1  (go back one commit)"
echo "  4. Restart the old backend"
echo ""
