#!/bin/bash
# =============================================================================
# Aurora Database Restore Script
# =============================================================================
# Usage: ./db-restore.sh [path/to/backup.sql]
# =============================================================================

set -e

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

# 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 "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

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 ""
read -p "Are you sure you want to proceed? (y/N): " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
  echo -e "${YELLOW}♻️  Restoring database...${NC}"
  
  if docker ps | grep -q aurora_db; then
     # Drop and recreate public schema to ensure clean slate, then restore
     # Note: dependent on how the dump was created. Standard pg_dump usually includes CREATE commands if configured, 
     # but often it's data only or structure+data. 
     # For safety, we'll just pipe the file to psql.
     
     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 -e "${RED}Error: Database container (aurora_db) is not running!${NC}"
     exit 1
  fi
else
  echo "Operation cancelled."
  exit 0
fi
