#!/bin/bash
# Restore the database from a backup file created by backup.sh.
#
# USAGE:
#   bash scripts/restore.sh backups/schoolly_backup_2026-08-25_020000.sql.gz
#
# WARNING: this REPLACES all current data in the database with the
# backup's contents. Existing data not in the backup is lost. Only run
# this when you're certain you want to roll back to that backup's state.

set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$SCRIPT_DIR"

if [ -z "$1" ]; then
  echo "Usage: bash scripts/restore.sh <path-to-backup.sql.gz>"
  echo ""
  echo "Available backups:"
  ls -1t backups/schoolly_backup_*.sql.gz 2>/dev/null || echo "  (none found in backups/)"
  exit 1
fi

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

if [ -f .env ]; then
  export $(grep -v '^#' .env | xargs)
fi

echo "⚠️  This will REPLACE ALL current data in database '$DB_NAME' with the contents of:"
echo "    $BACKUP_FILE"
read -p "Type 'yes' to continue: " CONFIRM
if [ "$CONFIRM" != "yes" ]; then
  echo "Cancelled."
  exit 0
fi

echo "Restoring..."
gunzip -c "$BACKUP_FILE" | PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "${DB_PORT:-5432}" -U "$DB_USER" -d "$DB_NAME"

echo "✅ Restore complete."
