"""Simple numbered SQL migration runner."""

from __future__ import annotations

from pathlib import Path

import asyncpg

MIGRATIONS_DIR = Path(__file__).parent / "migrations"


async def run_migrations(pool: asyncpg.Pool) -> list[str]:
    """Apply all unapplied migrations in order. Returns list of newly applied names."""
    async with pool.acquire() as conn:
        # Ensure tracking table exists
        await conn.execute("""
            CREATE TABLE IF NOT EXISTS _loom_migrations (
                name TEXT PRIMARY KEY,
                applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
            )
        """)

        # Get already-applied migrations
        applied = {
            row["name"]
            for row in await conn.fetch("SELECT name FROM _loom_migrations")
        }

    # Find and sort migration files
    sql_files = sorted(MIGRATIONS_DIR.glob("*.sql"))
    newly_applied: list[str] = []

    for sql_file in sql_files:
        if sql_file.name in applied:
            continue
        sql = sql_file.read_text()
        async with pool.acquire() as conn:
            async with conn.transaction():
                await conn.execute(sql)
                await conn.execute(
                    "INSERT INTO _loom_migrations (name) VALUES ($1)",
                    sql_file.name,
                )
        newly_applied.append(sql_file.name)

    return newly_applied
