#!/usr/bin/env bash
# Run Database Migrations for Token Aggregation Service

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
SERVICE_DIR="$SCRIPT_DIR/.."
MIGRATIONS_DIR="$HOME/projects/explorer-monorepo/backend/database/migrations"

# Load environment
if [[ -f "$SERVICE_DIR/.env" ]]; then
    set -a
    source "$SERVICE_DIR/.env"
    set +a
fi

DATABASE_URL="${DATABASE_URL:-postgresql://postgres:postgres@localhost:5432/explorer_db}"

echo "Running database migrations for Token Aggregation Service"
echo "Database: ${DATABASE_URL%%@*}"
echo ""

# Migration files
MIGRATION_0011="$MIGRATIONS_DIR/0011_token_aggregation_schema.up.sql"
MIGRATION_0012="$MIGRATIONS_DIR/0012_admin_config_schema.up.sql"
MIGRATION_0013="$MIGRATIONS_DIR/0013_update_token_logos_ipfs.up.sql"

# Check if migrations exist
if [[ ! -f "$MIGRATION_0011" ]]; then
    echo "❌ Migration 0011 not found: $MIGRATION_0011"
    exit 1
fi

if [[ ! -f "$MIGRATION_0012" ]]; then
    echo "❌ Migration 0012 not found: $MIGRATION_0012"
    exit 1
fi

# Test connection
if ! psql "$DATABASE_URL" -c "SELECT 1;" > /dev/null 2>&1; then
    echo "❌ Database connection failed"
    exit 1
fi

# Run migrations
echo "Running migration 0011: Token Aggregation Schema..."
psql "$DATABASE_URL" -f "$MIGRATION_0011"
echo "✅ Migration 0011 completed"

echo ""
echo "Running migration 0012: Admin Configuration Schema..."
psql "$DATABASE_URL" -f "$MIGRATION_0012"
echo "✅ Migration 0012 completed"

if [[ -f "$MIGRATION_0013" ]]; then
    echo ""
    echo "Running migration 0013: Update token logos to IPFS..."
    psql "$DATABASE_URL" -f "$MIGRATION_0013"
    echo "✅ Migration 0013 completed"
fi

echo ""
echo "✅ All migrations completed successfully"
