#!/bin/bash
# Script to run migrations in Docker PostgreSQL container
set -e

echo "Running Foxhunt migrations..."

# Wait for PostgreSQL to be ready
until pg_isready -U foxhunt -d foxhunt; do
  echo "Waiting for PostgreSQL..."
  sleep 1
done

# Connect as foxhunt user and run migrations in order
export PGUSER=foxhunt
export PGDATABASE=foxhunt

echo "Running migrations in order..."

# Run migrations in the correct order
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/001_up_create_trading_engine_tables.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/002_up_create_risk_performance_tables.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/003_up_create_wal_checkpoints.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/004_up_create_user_management.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/005_up_create_advanced_risk_management.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/006_up_create_performance_indexes.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/007_configuration_schema.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/008_initial_config_data.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/009_dual_provider_configuration.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/010_remove_polygon_configurations.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/011_create_market_data_tables.sql
psql -v ON_ERROR_STOP=1 -f /docker-entrypoint-initdb.d/migrations/012_create_event_and_config_tables.sql

echo "✅ All migrations completed successfully!"

# Create a marker file to indicate migrations are complete
touch /tmp/migrations_complete