#!/usr/bin/env bash
# Run database backup + clean-and-seed on PRODUCTION.
# Usage: on the production server, from repo root or backend:
#   ./backend/scripts/run-production-clean-and-seed.sh
# Or: bash backend/scripts/run-production-clean-and-seed.sh
#
# Requires: DATABASE_URL in environment or in backend/.env
# Requires: pg_dump (for backup) and Node/npm (for clean-and-seed)

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
REPO_ROOT="$(cd "$BACKEND_DIR/.." && pwd)"

# Load .env from backend if present
if [ -f "$BACKEND_DIR/.env" ]; then
  set -a
  source "$BACKEND_DIR/.env"
  set +a
fi

if [ -z "$DATABASE_URL" ]; then
  echo "❌ DATABASE_URL is not set. Set it in backend/.env or export it."
  exit 1
fi

echo "⚠️  This will TRUNCATE all tables and re-seed the database."
echo "   DATABASE_URL is set (database will be modified)."
echo ""
read -p "Type YES to continue: " confirm
if [ "$confirm" != "YES" ]; then
  echo "Aborted."
  exit 0
fi

BACKUP_DIR="${BACKUP_DIR:-$REPO_ROOT/backups}"
mkdir -p "$BACKUP_DIR"
BACKUP_FILE="$BACKUP_DIR/backup_before_cleanup_$(date +%Y%m%d_%H%M%S).sql"

echo "📦 Backing up database to $BACKUP_FILE ..."
if pg_dump "$DATABASE_URL" > "$BACKUP_FILE"; then
  echo "✅ Backup saved."
else
  echo "❌ Backup failed. Aborting."
  exit 1
fi

echo ""
echo "🧹 Running clean-and-seed..."
cd "$BACKEND_DIR"
npm run db:clean-and-seed

echo ""
echo "✅ Done. Restart the application so it uses the cleaned database."
echo "   System Administrator: admin@system.local (Password: Admin@123)"
