#!/bin/bash
set -e

echo "=== CORROSION REMOTE DEPLOYMENT ==="
echo ""

REPO_DIR="$HOME/corrosion-admin-panel"

# Step 1: Check if repo exists, clone or pull
if [ -d "$REPO_DIR" ]; then
    echo "📦 Updating repository..."
    cd "$REPO_DIR"
    git pull
else
    echo "📦 Cloning repository..."
    git clone git@git.corrosionmgmt.com:vantzs/corrosion-admin-panel.git "$REPO_DIR"
    cd "$REPO_DIR"
fi

echo "✅ Code updated"
echo ""

# Step 2: Create .env if needed
if [ ! -f docker/.env ]; then
    echo "📝 Creating docker/.env from template..."
    cp .env.example docker/.env

    # Generate secure keys
    JWT_SECRET=$(openssl rand -hex 32)
    ENCRYPTION_KEY=$(openssl rand -hex 32)

    # Update .env
    sed -i "s|JWT_SECRET=.*|JWT_SECRET=$JWT_SECRET|" docker/.env
    sed -i "s|ENCRYPTION_KEY=.*|ENCRYPTION_KEY=$ENCRYPTION_KEY|" docker/.env

    echo "✅ Created docker/.env"
    echo "⚠️  IMPORTANT: Edit docker/.env and add:"
    echo "   - CLOUDFLARE_API_TOKEN"
    echo "   - STEAM_API_KEY"
    echo "   - PAYPAL_CLIENT_ID"
    echo "   - PAYPAL_CLIENT_SECRET"
    echo ""
    read -p "Press Enter after updating docker/.env..."
fi

# Step 3: Stop existing containers (if any)
echo "🛑 Stopping existing containers..."
cd docker
docker compose down || true

# Step 4: Rebuild and start
echo "🚀 Building and starting services..."
docker compose up -d --build

echo ""
echo "⏳ Waiting for database to be ready..."
sleep 15

# Step 5: Check which migrations have been run
echo ""
echo "📊 Checking migration status..."
cd ..

CURRENT_MIGRATIONS=$(docker exec corrosion-db psql -U corrosion -d corrosion -t -c "SELECT version FROM _sqlx_migrations ORDER BY version;" 2>/dev/null || echo "")

if [ -z "$CURRENT_MIGRATIONS" ]; then
    echo "⚠️  No migrations table found - running ALL migrations"
    for migration in backend/migrations/*.sql; do
        echo "Running $(basename $migration)..."
        docker exec -i corrosion-db psql -U corrosion -d corrosion < "$migration"
    done
else
    echo "Current migrations:"
    echo "$CURRENT_MIGRATIONS"
    echo ""

    # Run only new migrations (009-012)
    for version in 009 010 011 012; do
        if echo "$CURRENT_MIGRATIONS" | grep -q "^[[:space:]]*$version"; then
            echo "✅ Migration $version already applied"
        else
            migration_file=$(ls backend/migrations/${version}_*.sql 2>/dev/null || true)
            if [ -n "$migration_file" ]; then
                echo "📊 Running migration $version..."
                docker exec -i corrosion-db psql -U corrosion -d corrosion < "$migration_file"
                echo "✅ Migration $version complete"
            else
                echo "⚠️  Migration $version not found"
            fi
        fi
    done
fi

echo ""
echo "=== DEPLOYMENT COMPLETE ==="
echo ""
echo "Services status:"
docker ps --filter "name=corrosion-" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

echo ""
echo "Health check:"
curl -s http://localhost:8088/api/health || echo "⚠️  API not responding yet (may need a few more seconds)"

echo ""
echo "View logs:"
echo "  docker logs -f corrosion-api"
echo "  docker logs -f corrosion-nginx"
echo ""
