#!/usr/bin/env bash

set -euo pipefail

# ========================================
# MIGRATION RESET UTILITY SCRIPT
# ========================================

log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

log "🔄 Migration Reset Utility"
log "This script will reset migration state to allow re-running migrations"

# Check if DATABASE_URL is set
if [ -z "${DATABASE_URL:-}" ]; then
  log "ERROR: DATABASE_URL environment variable is required"
  exit 1
fi

# Get confirmation from user
echo ""
echo "⚠️  WARNING: This will:"
echo "   - Clear the schema_migrations table"
echo "   - Remove the migration completion marker"
echo "   - Allow migrations to run again on next docker compose up"
echo ""
echo "   This will NOT delete your actual data tables."
echo ""
read -p "Are you sure you want to proceed? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  log "Operation cancelled"
  exit 0
fi

log "🗑️  Clearing migration state..."

# Connect to database and clear migration tracking
psql "${DATABASE_URL}" -c "
  DROP TABLE IF EXISTS schema_migrations;
  SELECT 'Migration tracking table dropped' as status;
" || {
  log "ERROR: Failed to clear database migration state"
  exit 1
}

# Remove migration marker file
MIGRATION_MARKER="/tmp/migrations-completed"
if [ -f "${MIGRATION_MARKER}" ]; then
  rm -f "${MIGRATION_MARKER}"
  log "📝 Removed migration completion marker"
else
  log "📝 Migration completion marker not found (already clean)"
fi

log "✅ Migration state reset complete!"
log "💡 Next 'docker compose up' will re-run all migrations"
