#!/usr/bin/env bash
# Complete Setup Script for Token Aggregation Service
# This script runs database migrations and prepares the service for deployment

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SERVICE_DIR="$SCRIPT_DIR/.."
MIGRATIONS_DIR="$PROJECT_ROOT/explorer-monorepo/backend/database/migrations"

echo "=========================================="
echo "Token Aggregation Service - Complete Setup"
echo "=========================================="
echo ""

# Load environment variables
if [[ -f "$SERVICE_DIR/.env" ]]; then
    echo "Loading environment from .env file..."
    set -a
    source "$SERVICE_DIR/.env"
    set +a
fi

# Database configuration
DATABASE_URL="${DATABASE_URL:-postgresql://postgres:postgres@localhost:5432/explorer_db}"

echo "Database URL: ${DATABASE_URL%%@*}" # Show without password
echo ""

# Step 1: Verify migrations exist
echo "Step 1: Verifying migration files..."
MIGRATION_0011="$MIGRATIONS_DIR/0011_token_aggregation_schema.up.sql"
MIGRATION_0012="$MIGRATIONS_DIR/0012_admin_config_schema.up.sql"

if [[ ! -f "$MIGRATION_0011" ]]; then
    echo "❌ Migration 0011 not found: $MIGRATION_0011"
    exit 1
fi

if [[ ! -f "$MIGRATION_0012" ]]; then
    echo "❌ Migration 0012 not found: $MIGRATION_0012"
    exit 1
fi

echo "✅ Migration files found"
echo ""

# Step 2: Test database connection
echo "Step 2: Testing database connection..."
if psql "$DATABASE_URL" -c "SELECT 1;" > /dev/null 2>&1; then
    echo "✅ Database connection successful"
else
    echo "❌ Database connection failed"
    echo "Please verify:"
    echo "  - PostgreSQL is running"
    echo "  - DATABASE_URL is correct in .env file"
    echo "  - Database credentials are valid"
    exit 1
fi
echo ""

# Step 3: Check if migrations already applied
echo "Step 3: Checking migration status..."
MIGRATION_0011_APPLIED=$(psql "$DATABASE_URL" -tAc "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'token_market_data');" 2>/dev/null || echo "false")
MIGRATION_0012_APPLIED=$(psql "$DATABASE_URL" -tAc "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'api_keys');" 2>/dev/null || echo "false")

if [[ "$MIGRATION_0011_APPLIED" == "t" ]]; then
    echo "⚠️  Migration 0011 (token aggregation) already applied"
else
    echo "📋 Migration 0011 (token aggregation) needs to be applied"
fi

if [[ "$MIGRATION_0012_APPLIED" == "t" ]]; then
    echo "⚠️  Migration 0012 (admin config) already applied"
else
    echo "📋 Migration 0012 (admin config) needs to be applied"
fi
echo ""

# Step 4: Run migrations
echo "Step 4: Running database migrations..."

if [[ "$MIGRATION_0011_APPLIED" != "t" ]]; then
    echo "Running migration 0011: Token Aggregation Schema..."
    if psql "$DATABASE_URL" -f "$MIGRATION_0011"; then
        echo "✅ Migration 0011 completed successfully"
    else
        echo "❌ Migration 0011 failed"
        exit 1
    fi
    echo ""
else
    echo "⏭️  Skipping migration 0011 (already applied)"
    echo ""
fi

if [[ "$MIGRATION_0012_APPLIED" != "t" ]]; then
    echo "Running migration 0012: Admin Configuration Schema..."
    if psql "$DATABASE_URL" -f "$MIGRATION_0012"; then
        echo "✅ Migration 0012 completed successfully"
    else
        echo "❌ Migration 0012 failed"
        exit 1
    fi
    echo ""
else
    echo "⏭️  Skipping migration 0012 (already applied)"
    echo ""
fi

# Step 5: Verify migrations
echo "Step 5: Verifying migrations..."
TOKEN_TABLES=$(psql "$DATABASE_URL" -tAc "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('token_market_data', 'liquidity_pools', 'token_ohlcv');" 2>/dev/null || echo "0")
ADMIN_TABLES=$(psql "$DATABASE_URL" -tAc "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('api_keys', 'api_endpoints', 'admin_users');" 2>/dev/null || echo "0")

echo "Token aggregation tables: $TOKEN_TABLES/3"
echo "Admin configuration tables: $ADMIN_TABLES/3"

if [[ "$TOKEN_TABLES" -ge "3" && "$ADMIN_TABLES" -ge "3" ]]; then
    echo "✅ All migrations verified successfully"
else
    echo "⚠️  Some tables may be missing"
fi
echo ""

# Step 6: Check for admin users
echo "Step 6: Checking for admin users..."
ADMIN_COUNT=$(psql "$DATABASE_URL" -tAc "SELECT COUNT(*) FROM admin_users WHERE is_active = true;" 2>/dev/null || echo "0")

if [[ "$ADMIN_COUNT" -eq "0" ]]; then
    echo "⚠️  No admin users found"
    echo ""
    echo "Next step: Create an admin user"
    echo "  Run: ./scripts/create-admin-user.sh"
    echo ""
else
    echo "✅ Found $ADMIN_COUNT active admin user(s)"
    echo ""
fi

# Step 7: Verify service files
echo "Step 7: Verifying service files..."
if [[ -f "$SERVICE_DIR/src/index.ts" ]]; then
    echo "✅ Backend service files found"
else
    echo "❌ Backend service files missing"
    exit 1
fi

if [[ -f "$SERVICE_DIR/frontend/src/App.tsx" ]]; then
    echo "✅ Frontend files found"
else
    echo "❌ Frontend files missing"
    exit 1
fi

if [[ -f "$SERVICE_DIR/package.json" ]]; then
    echo "✅ Service configuration found"
else
    echo "❌ Service configuration missing"
    exit 1
fi
echo ""

# Summary
echo "=========================================="
echo "Setup Complete!"
echo "=========================================="
echo ""
echo "✅ Database migrations: Applied"
echo "✅ Service files: Verified"
echo ""

if [[ "$ADMIN_COUNT" -eq "0" ]]; then
    echo "📋 Next Steps:"
    echo ""
    echo "1. Create admin user:"
    echo "   cd $SERVICE_DIR"
    echo "   ./scripts/create-admin-user.sh"
    echo ""
    echo "2. Deploy to Proxmox (if on Proxmox host):"
    echo "   ./scripts/deploy-to-proxmox.sh"
    echo ""
    echo "3. Or run locally:"
    echo "   npm install"
    echo "   npm run build"
    echo "   npm start"
    echo ""
else
    echo "📋 Next Steps:"
    echo ""
    echo "1. Deploy to Proxmox (if on Proxmox host):"
    echo "   cd $SERVICE_DIR"
    echo "   ./scripts/deploy-to-proxmox.sh"
    echo ""
    echo "2. Or run locally:"
    echo "   npm install"
    echo "   npm run build"
    echo "   npm start"
    echo ""
    echo "3. Access control panel:"
    echo "   http://localhost:3000 (API)"
    echo "   http://localhost:3001 (Frontend in dev mode)"
    echo ""
fi

echo "=========================================="
