#!/bin/bash

# Configuration
REMOTE_HOST="root@infra.mintel.me"
REMOTE_DIR="/opt/infra/directus"

# DB Details (matching docker-compose defaults)
DB_USER="directus"
DB_NAME="directus"

ACTION=$1
ENV=$2

# Help
if [ -z "$ACTION" ] || [ -z "$ENV" ]; then
    echo "Usage: ./scripts/sync-directus.sh [push|pull] [infra|testing|staging|production]"
    echo ""
    echo "Commands:"
    echo "  push   Sync LOCAL data -> REMOTE"
    echo "  pull   Sync REMOTE data -> LOCAL"
    echo ""
    echo "Environments:"
    echo "  infra (infra.mintel.me)"
    exit 1
fi

# Map Environment
case $ENV in
  infra)
    PROJECT_NAME="directus"
    ;;
  *)
    echo "❌ Invalid environment: $ENV. Only 'infra' is currently configured for monorepo sync."
    exit 1
    ;;
esac

# Detect local containers
echo "🔍 Detecting local database..."
LOCAL_DB_CONTAINER=$(docker compose ps -q at-mintel-directus-db)
if [ -z "$LOCAL_DB_CONTAINER" ]; then
    echo "❌ Local directus-db container not found. Is it running? (npm run dev)"
    exit 1
fi

if [ "$ACTION" == "push" ]; then
    echo "🚀 Pushing Local Data to $ENV..."
    
    # 1. DB Dump
    echo "📦 Dumping local database..."
    docker exec "$LOCAL_DB_CONTAINER" pg_dump -U "$DB_USER" --clean --if-exists --no-owner --no-privileges "$DB_NAME" > dump.sql
    
    # 2. Upload Dump
    echo "📤 Uploading dump to remote server..."
    scp dump.sql "$REMOTE_HOST:$REMOTE_DIR/dump.sql"
    
    # 3. Restore on Remote
    echo "🔄 Restoring dump on $ENV..."
    REMOTE_DB_CONTAINER=$(ssh "$REMOTE_HOST" "cd $REMOTE_DIR && docker compose -p $PROJECT_NAME ps -q directus-postgres")

    if [ -z "$REMOTE_DB_CONTAINER" ]; then
        echo "❌ Remote $ENV-db container not found!"
        exit 1
    fi

    # Wipe remote DB clean before restore to avoid constraint errors
    echo "🧹 Wiping remote database schema..."
    ssh "$REMOTE_HOST" "docker exec $REMOTE_DB_CONTAINER psql -U $DB_USER $DB_NAME -c 'DROP SCHEMA public CASCADE; CREATE SCHEMA public;'"
    
    echo "⚡ Restoring database..."
    ssh "$REMOTE_HOST" "docker exec -i $REMOTE_DB_CONTAINER psql -U $DB_USER $DB_NAME < $REMOTE_DIR/dump.sql"
    
    # 4. Sync Uploads
    echo "📁 Syncing uploads (Local -> $ENV)..."
    rsync -avz --progress ./directus/uploads/ "$REMOTE_HOST:$REMOTE_DIR/uploads/"
    
    # Clean up
    rm dump.sql
    ssh "$REMOTE_HOST" "rm $REMOTE_DIR/dump.sql"
    
    # 5. Restart Directus to trigger migrations and refresh schema cache
    echo "🔄 Restarting remote Directus to apply migrations..."
    ssh "$REMOTE_HOST" "cd $REMOTE_DIR && docker compose -p $PROJECT_NAME restart directus"
    
    echo "✨ Push to $ENV complete!"

elif [ "$ACTION" == "pull" ]; then
    echo "📥 Pulling $ENV Data to Local..."
    
    # 1. DB Dump on Remote
    echo "📦 Dumping remote database ($ENV)..."
    REMOTE_DB_CONTAINER=$(ssh "$REMOTE_HOST" "cd $REMOTE_DIR && docker compose -p $PROJECT_NAME ps -q directus-postgres")

    if [ -z "$REMOTE_DB_CONTAINER" ]; then
        echo "❌ Remote $ENV-db container not found!"
        exit 1
    fi
    ssh "$REMOTE_HOST" "docker exec $REMOTE_DB_CONTAINER pg_dump -U $DB_USER --clean --if-exists --no-owner --no-privileges $DB_NAME > $REMOTE_DIR/dump.sql"
    
    # 2. Download Dump
    echo "📥 Downloading dump..."
    scp "$REMOTE_HOST:$REMOTE_DIR/dump.sql" dump.sql
    
    # Wipe local DB clean before restore to avoid constraint errors
    echo "🧹 Wiping local database schema..."
    docker exec "$LOCAL_DB_CONTAINER" psql -U "$DB_USER" "$DB_NAME" -c 'DROP SCHEMA public CASCADE; CREATE SCHEMA public;'
    
    echo "⚡ Restoring database locally..."
    docker exec -i "$LOCAL_DB_CONTAINER" psql -U "$DB_USER" "$DB_NAME" < dump.sql
    
    # 4. Sync Uploads
    echo "📁 Syncing uploads ($ENV -> Local)..."
    rsync -avz --progress "$REMOTE_HOST:$REMOTE_DIR/uploads/" ./directus/uploads/
    
    # Clean up
    rm dump.sql
    ssh "$REMOTE_HOST" "rm $REMOTE_DIR/dump.sql"
    
    echo "✨ Pull to Local complete!"
else
    echo "Invalid action: $ACTION. Use push or pull."
    exit 1
fi
