#!/bin/bash
set -e

# Config
DB_NAME="veza_test_verify_migrations"
CONTAINER_NAME="veza_postgres_verify"
DB_PORT="5433"

echo "🚀 Starting Migration Verification..."

# Check if container exists and remove it
if [ "$(docker ps -a -q -f name=$CONTAINER_NAME)" ]; then
    echo "Cleaning up old container..."
    docker rm -f $CONTAINER_NAME
fi

# 1. Start Postgres
echo "🐳 Starting clean Postgres container..."
docker run -d --name $CONTAINER_NAME -e POSTGRES_PASSWORD=veza -e POSTGRES_USER=veza -e POSTGRES_DB=$DB_NAME -p $DB_PORT:5432 postgres:15-alpine

# Wait for it
echo "⏳ Waiting for Postgres to be ready..."
until docker exec $CONTAINER_NAME pg_isready -U veza > /dev/null 2>&1; do
  echo "Waiting..."
  sleep 1
done
sleep 2 # Extra safety

# 2. Run Migrations UP
echo "⬆️ Running Migrations (UP)..."
export DB_HOST=localhost
export DB_PORT=$DB_PORT
export DB_NAME=$DB_NAME
export DB_USER=veza
export DB_PASSWORD=veza

cd veza-backend-api && go run cmd/migrate_tool/main.go
cd ..

# 3. Simulate DOWN (Drop all tables)
echo "⬇️ Simulating DOWN (Drop all tables)..."
docker exec $CONTAINER_NAME psql -U veza -d $DB_NAME -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"

# 4. Run Migrations UP again
echo "🔄 Re-applying Migrations (UP)..."
cd veza-backend-api && go run cmd/migrate_tool/main.go
cd ..

# Cleanup
echo "🧹 Cleaning up..."
docker rm -f $CONTAINER_NAME

echo "✅ Migration verification passed!"
