#!/bin/bash

# Database Reset Script
# Resets PostgreSQL databases to initial state

set -e

echo "⚠️  WARNING: This will reset ALL databases!"
read -p "Are you sure? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Cancelled."
    exit 1
fi

echo "🔄 Resetting PostgreSQL databases..."

# Stop backend and CMS to avoid connection issues
echo "Stopping backend and CMS containers..."
docker stop placebo-backend-dev placebo-cms-dev 2>/dev/null || true

# Drop and recreate databases
echo "Resetting databases..."
docker exec placebo-postgres-dev psql -U placebo_user -c "DROP DATABASE IF EXISTS placebo_backend_db;" postgres
docker exec placebo-postgres-dev psql -U placebo_user -c "DROP DATABASE IF EXISTS placebo_cms_db;" postgres
docker exec placebo-postgres-dev psql -U placebo_user -c "CREATE DATABASE placebo_backend_db;" postgres
docker exec placebo-postgres-dev psql -U placebo_user -c "CREATE DATABASE placebo_cms_db;" postgres

# Run initialization script
echo "Running initialization script..."
docker exec placebo-postgres-dev psql -U placebo_user -f /docker-entrypoint-initdb.d/init-postgres-dev.sql postgres

# Restart containers
echo "Restarting containers..."
docker start placebo-backend-dev placebo-cms-dev 2>/dev/null || true

echo "✅ Databases reset successfully!"
echo ""
echo "Note: Backend and CMS will need to restart their services."
echo "For backend: docker restart placebo-backend-dev"
echo "For CMS: docker restart placebo-cms-dev"