#!/bin/bash
# Run migration 0010_track_schema.up.sql

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
MIGRATION_DIR="$PROJECT_ROOT/backend/database/migrations"
MIGRATION_FILE="$MIGRATION_DIR/0010_track_schema.up.sql"

echo "=== Running Track Schema Migration (0010) ==="
echo ""

# Check if migration file exists
if [ ! -f "$MIGRATION_FILE" ]; then
    echo "❌ Migration file not found: $MIGRATION_FILE"
    exit 1
fi

# Load database config from environment or use defaults
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_USER="${DB_USER:-explorer}"
DB_PASSWORD="${DB_PASSWORD:-changeme}"
DB_NAME="${DB_NAME:-explorer}"

echo "Database: $DB_NAME@$DB_HOST:$DB_PORT"
echo "User: $DB_USER"
echo ""

# Run migration using psql
export PGPASSWORD="$DB_PASSWORD"

if psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -f "$MIGRATION_FILE"; then
    echo ""
    echo "✅ Migration 0010_track_schema.up.sql completed successfully"
    echo ""
    echo "Created tables:"
    echo "  - addresses (Track 2)"
    echo "  - token_transfers (Track 2)"
    echo "  - token_balances (Track 2)"
    echo "  - internal_transactions (Track 2)"
    echo "  - analytics_flows (Track 3)"
    echo "  - analytics_bridge_history (Track 3)"
    echo "  - token_distribution (Track 3 - materialized view)"
    echo "  - operator_events (Track 4)"
    echo "  - operator_ip_whitelist (Track 4)"
    echo "  - operator_roles (Track 4)"
    echo "  - wallet_nonces (Authentication)"
else
    echo ""
    echo "❌ Migration failed"
    exit 1
fi

unset PGPASSWORD

