#!/bin/bash

ENV=$1
REMOTE_HOST="root@alpha.mintel.me"
REMOTE_DIR="/home/deploy/sites/klz-cables.com"

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

PRJ_ID=$(jq -r .name package.json | sed 's/@mintel\///' | sed 's/\.com$//' | sed 's/-nextjs$//' | sed 's/-cables$//')

case $ENV in
  local)
    CONTAINER=$(docker compose ps -q directus-cms)
    if [ -z "$CONTAINER" ]; then
        echo "❌ Local directus container not found."
        exit 1
    fi
    echo "🚀 Applying schema locally..."
    docker exec "$CONTAINER" npx directus schema apply /directus/schema/snapshot.yaml --yes
    ;;
  testing|staging|production)
    case $ENV in
      testing)    PROJECT_NAME="${PRJ_ID}-testing" ;;
      staging)    PROJECT_NAME="${PRJ_ID}-staging" ;;
      production) 
        PROJECT_NAME="${PRJ_ID}-production"
        OLD_PROJECT_NAME="${PRJ_ID}-prod" # Fallback for previous convention
        ;;
    esac
    
    echo "📤 Uploading snapshot to $ENV..."
    scp ./directus/schema/snapshot.yaml "$REMOTE_HOST:$REMOTE_DIR/directus/schema/snapshot.yaml"
    
    echo "🔍 Detecting remote container..."
    REMOTE_CONTAINER=$(ssh "$REMOTE_HOST" "cd $REMOTE_DIR && docker compose -p $PROJECT_NAME ps -q directus")
    
    if [ -z "$REMOTE_CONTAINER" ] && [ -n "$OLD_PROJECT_NAME" ]; then
        echo "⚠️ $PROJECT_NAME not found, trying fallback $OLD_PROJECT_NAME..."
        REMOTE_CONTAINER=$(ssh "$REMOTE_HOST" "cd $REMOTE_DIR && docker compose -p $OLD_PROJECT_NAME ps -q directus")
        if [ -n "$REMOTE_CONTAINER" ]; then
            PROJECT_NAME=$OLD_PROJECT_NAME
        fi
    fi

    if [ -z "$REMOTE_CONTAINER" ]; then
        echo "❌ Remote container for $ENV not found (checked $PROJECT_NAME)."
        exit 1
    fi
    
    echo "🚀 Applying schema to $ENV..."
    ssh "$REMOTE_HOST" "docker exec $REMOTE_CONTAINER npx directus schema apply /directus/schema/snapshot.yaml --yes"
    
    echo "🔄 Restarting Directus to clear cache..."
    ssh "$REMOTE_HOST" "cd $REMOTE_DIR && docker compose -p $PROJECT_NAME restart directus"
    ;;
  *)
    echo "❌ Invalid environment."
    exit 1
    ;;
esac

echo "✨ Schema apply complete!"
