#!/bin/bash
# Run Alembic migrations with database connectivity check

set -e

echo "Running Alembic migrations..."

# Check if database is reachable
echo "Checking database connectivity..."
until python -c "
import asyncio
from sqlalchemy.ext.asyncio import create_async_engine

async def check():
    engine = create_async_engine('postgresql+asyncpg://mtgonline:mtgonline_pass@postgres:5432/mtgonline')
    async with engine.connect() as conn:
        await conn.execute(sqlalchemy.text('SELECT 1'))
    await engine.dispose()
    print('Database connection successful')

import sqlalchemy
asyncio.run(check())
" 2>/dev/null; do
    echo "Waiting for database to be ready..."
    sleep 2
done

# Run migrations
echo "Applying migrations..."
alembic upgrade head

echo "Migrations completed successfully!"
