#!/usr/bin/env bash
# ────────────────────────────────────────────────────────────────────────────
# Payload CMS Database Restore
# Restores a backup created by backup-db.sh
# Usage: npm run restore:db -- backups/payload_20260224_191900.sql.gz
# ────────────────────────────────────────────────────────────────────────────
set -euo pipefail

# Load environment variables
if [ -f .env ]; then
  set -a; source .env; set +a
fi

DB_NAME="${PAYLOAD_DB_NAME:-payload}"
DB_USER="${PAYLOAD_DB_USER:-payload}"
DB_CONTAINER="klz-2026-klz-db-1"

BACKUP_FILE="${1:-}"

if [ -z "$BACKUP_FILE" ]; then
  echo "❌ Usage: npm run restore:db -- <backup-file>"
  echo ""
  echo "📋 Available backups:"
  ls -lh backups/*.sql.gz 2>/dev/null | awk '{print "   " $NF " (" $5 ")"}' || echo "   No backups found."
  exit 1
fi

if [ ! -f "$BACKUP_FILE" ]; then
  echo "❌ Backup file not found: $BACKUP_FILE"
  exit 1
fi

# Check if container is running
if ! docker ps --format '{{.Names}}' | grep -q "$DB_CONTAINER"; then
  echo "❌ Database container '$DB_CONTAINER' is not running."
  echo "   Start it with: docker compose up -d klz-db"
  exit 1
fi

echo "⚠️  WARNING: This will REPLACE ALL DATA in the '$DB_NAME' database!"
echo "   Backup file: $BACKUP_FILE"
echo ""
read -p "Are you sure? (y/N) " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo "Cancelled."
  exit 0
fi

echo "🔄 Restoring database from $BACKUP_FILE..."
gunzip -c "$BACKUP_FILE" | docker exec -i "$DB_CONTAINER" psql -U "$DB_USER" -d "$DB_NAME" --quiet

echo "✅ Database restored successfully!"
