#!/bin/bash
# =============================================================================
# Aurora Database Restore Script
# =============================================================================
# Restores the database from a SQL backup file.
# Automatically creates a safety backup before overwriting.
#
# Usage: ./db-restore.sh <path-to-backup.sql>
# =============================================================================

set -e

# Load environment variables safely
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib/load-env.sh"
load_env

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

if [ -z "$1" ]; then
  echo -e "${RED}Error: Please specify the backup file to restore.${NC}"
  echo "Usage: ./db-restore.sh <path-to-sql-file>"
  echo ""
  echo "Available backups:"
  ls -lh shared/db/backups/*.sql 2>/dev/null || echo "  (No backups found in shared/db/backups)"
  exit 1
fi

BACKUP_FILE="$1"

if [ ! -f "$BACKUP_FILE" ]; then
  echo -e "${RED}Error: File not found: $BACKUP_FILE${NC}"
  exit 1
fi

# Validate the backup file looks like SQL
if ! head -1 "$BACKUP_FILE" | grep -qiE '(^--|^SET|^CREATE|^INSERT|^\\\\connect|^pg_dump)'; then
  echo -e "${YELLOW}⚠️  Warning: File does not appear to be a SQL dump.${NC}"
  read -p "Continue anyway? (y/N): " -n 1 -r
  echo ""
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Operation cancelled."
    exit 0
  fi
fi

echo -e "${YELLOW}⚠️  WARNING: This will OVERWRITE the current database!${NC}"
echo -e "Target Database: ${DB_NAME:-auroradev}"
echo -e "Backup File:     $BACKUP_FILE"
echo -e "File Size:       $(du -h "$BACKUP_FILE" | cut -f1)"
echo ""
read -p "Are you sure you want to proceed? (y/N): " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
  if ! docker ps | grep -q aurora_db; then
    echo -e "${RED}Error: Database container (aurora_db) is not running!${NC}"
    exit 1
  fi

  # Create a safety backup before restoring
  echo -e "${YELLOW}💾 Creating safety backup before restore...${NC}"
  bash "$SCRIPT_DIR/db-backup.sh" || {
    echo -e "${RED}⚠️  Safety backup failed. Aborting restore.${NC}"
    exit 1
  }

  echo -e "${YELLOW}♻️  Restoring database...${NC}"
  cat "$BACKUP_FILE" | docker exec -i aurora_db psql -U "${DB_USER:-auroradev}" -d "${DB_NAME:-auroradev}"
  
  echo -e "  ${GREEN}✓${NC} Restore complete!"
else
  echo "Operation cancelled."
  exit 0
fi
