import asyncio
import os
from pathlib import Path

import asyncpg


async def main() -> None:
    root = Path(__file__).resolve().parents[1]
    conn = await asyncpg.connect(os.environ["DATABASE_URL"])
    try:
        await conn.execute(
            "CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())"
        )
        for path in sorted((root / "db" / "migrations").glob("*.sql")):
            exists = await conn.fetchval("SELECT 1 FROM schema_migrations WHERE version=$1", path.name)
            if exists:
                continue
            async with conn.transaction():
                await conn.execute(path.read_text(encoding="utf-8"))
                await conn.execute("INSERT INTO schema_migrations(version) VALUES($1)", path.name)
            print(f"applied {path.name}")
    finally:
        await conn.close()


if __name__ == "__main__":
    asyncio.run(main())
