#!/bin/bash

# Configuration
PROJECT="infra-cms"
LOCAL_SCHEMA_PATH="./packages/cms-infra/schema/snapshot.yaml"
REMOTE_HOST="root@infra.mintel.me"
REMOTE_DIR="/opt/infra/directus"

ENV=$1

if [ -z "$ENV" ]; then
    echo "Usage: ./scripts/cms-apply.sh [local|infra]"
    exit 1
fi

case $ENV in
  local)
    PROJECT="infra-cms"
    # Derive monorepo root
    SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    ROOT_DIR="$( dirname "$SCRIPT_DIR" )"
    CMD_PREFIX="docker compose -f $ROOT_DIR/packages/cms-infra/docker-compose.yml"
    
    LOCAL_CONTAINER=$($CMD_PREFIX ps -q $PROJECT)
    if [ -z "$LOCAL_CONTAINER" ]; then
        echo "❌ Local $PROJECT container not found. Is it running?"
        exit 1
    fi

    echo "🧹 Reconciling database metadata..."
    ./scripts/cms-reconcile.sh

    echo "🚀 Applying schema to LOCAL $PROJECT..."
    docker exec "$LOCAL_CONTAINER" npx directus schema apply -y /directus/schema/snapshot.yaml
    ;;
  infra)
    # 'infra' is the remote production server for at-mintel
    PROJECT="directus" # Remote project name
    
    echo "🔍 Detecting remote container..."
    REMOTE_CONTAINER=$(ssh "$REMOTE_HOST" "docker ps --filter label=com.docker.compose.project=$PROJECT --filter label=com.docker.compose.service=directus -q")
    
    if [ -z "$REMOTE_CONTAINER" ]; then
        # Fallback to older name if labels fail
        REMOTE_CONTAINER=$(ssh "$REMOTE_HOST" "docker ps -f name=directus-directus-1 -q")
    fi

    if [ -z "$REMOTE_CONTAINER" ]; then
        echo "❌ Remote container for $ENV not found."
        exit 1
    fi

    echo "📦 Syncing extensions to REMOTE $ENV..."
    # Ensure remote directory exists
    ssh "$REMOTE_HOST" "mkdir -p $REMOTE_DIR/extensions"
    rsync -avz --delete ./packages/cms-infra/extensions/ "$REMOTE_HOST:$REMOTE_DIR/extensions/"
    
    echo "📤 Injecting snapshot directly into container $REMOTE_CONTAINER..."
    # Inject file via stdin to avoid needing a host-side mount or scp path matching
    ssh "$REMOTE_HOST" "docker exec -i $REMOTE_CONTAINER sh -c 'cat > /tmp/snapshot.yaml'" < "$LOCAL_SCHEMA_PATH"
    
    echo "🚀 Applying schema to REMOTE $ENV..."
    ssh "$REMOTE_HOST" "docker exec $REMOTE_CONTAINER npx directus schema apply -y /tmp/snapshot.yaml"
    
    echo "🔄 Restarting remote Directus to clear cache..."
    ssh "$REMOTE_HOST" "cd $REMOTE_DIR && docker compose restart directus"
    
    # Cleanup
    ssh "$REMOTE_HOST" "docker exec $REMOTE_CONTAINER rm /tmp/snapshot.yaml"
    ;;
  *)
    echo "❌ Invalid environment: $ENV. Supported: local, infra."
    exit 1
    ;;
esac

echo "✨ Schema apply complete!"
