#!/bin/bash

# Database Restore Script
# Restores PostgreSQL databases from backup

set -e

if [ $# -eq 0 ]; then
    echo "Usage: $0 <backup_file> [database_name]"
    echo "Example: $0 backups/backend_db_20250101_120000.sql"
    echo "Example: $0 backups/backend_db_20250101_120000.sql placebo_backend_db"
    exit 1
fi

BACKUP_FILE="$1"
DATABASE="${2:-placebo_backend_db}"

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

echo "🔄 Restoring database $DATABASE from $BACKUP_FILE..."

# Drop and recreate database
echo "Recreating database..."
docker exec placebo-postgres-dev psql -U placebo_user -c "DROP DATABASE IF EXISTS $DATABASE;" postgres
docker exec placebo-postgres-dev psql -U placebo_user -c "CREATE DATABASE $DATABASE;" postgres

# Restore from backup
echo "Restoring data..."
docker exec -i placebo-postgres-dev psql -U placebo_user -d "$DATABASE" < "$BACKUP_FILE"

echo "✅ Database $DATABASE restored successfully!"