#!/bin/bash
set -e

DB_NAME="veza_migrations_v1_test"
DB_USER="postgres"
DB_HOST="localhost"
MIGRATIONS_DIR="veza-backend-api/migrations"

echo "🔄 Resetting Test Database: $DB_NAME..."

# Drop and Create DB
echo "💣 Dropping database $DB_NAME..."
dropdb --if-exists -h $DB_HOST -U $DB_USER $DB_NAME
echo "✨ Creating database $DB_NAME..."
createdb -h $DB_HOST -U $DB_USER $DB_NAME

# Run Migrations
echo "🚀 Running V1 Migrations..."

for file in $(ls $MIGRATIONS_DIR/*.sql | sort); do
    echo "   ➡️ Applying $(basename $file)..."
    psql -h $DB_HOST -U $DB_USER -d $DB_NAME -f "$file" > /dev/null
done

echo "✅ All migrations applied successfully!"

# Validation
echo "🔍 Verifying Schema..."
TABLE_COUNT=$(psql -h $DB_HOST -U $DB_USER -d $DB_NAME -t -c "SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public';")
echo "📊 Total Tables in Public Schema: $TABLE_COUNT"

if [ "$TABLE_COUNT" -lt 10 ]; then
    echo "❌ Error: Too few tables created."
    exit 1
fi

echo "🎉 Verification Complete. The V1 migrations are valid."
