"""Tests for migration registry and discovery."""

from __future__ import annotations

import pytest

from repo_core.migrations.registry import get_postgres_migrations, get_doris_migrations
from repo_core.migrations.runner import Migration


# ===========================================================================
# Registry
# ===========================================================================


def test_get_postgres_migrations_returns_list():
    migrations = get_postgres_migrations()
    assert isinstance(migrations, list)
    assert len(migrations) > 0
    assert all(isinstance(m, Migration) for m in migrations)


def test_get_doris_migrations_returns_list():
    migrations = get_doris_migrations()
    assert isinstance(migrations, list)
    assert len(migrations) > 0
    assert all(isinstance(m, Migration) for m in migrations)


def test_migrations_have_required_fields():
    for m in get_postgres_migrations():
        assert m.version, f"Migration missing version"
        assert m.description, f"Migration {m.version} missing description"
        assert m.up is not None, f"Migration {m.version} missing up op"
        assert m.down is not None, f"Migration {m.version} missing down op"
        # up op produces SQL
        sql = m.up.sql()
        assert len(sql) > 0, f"Migration {m.version} up produces no SQL"


def test_versions_are_unique():
    versions = [m.version for m in get_postgres_migrations()]
    assert len(versions) == len(set(versions)), f"Duplicate versions: {versions}"


def test_discovery_sorts_by_filename():
    """Migrations are discovered in filename order, which is the execution order."""
    from repo_core.migrations.discovery import discover_migrations
    pg = discover_migrations("postgresql")
    # The first migration should be from 0001 file (initial setup)
    assert len(pg) > 0


def test_up_to_file_filter():
    from repo_core.migrations.discovery import discover_migrations
    all_migs = discover_migrations("postgresql")
    subset = discover_migrations("postgresql", up_to_file="0001")
    # up_to_file=0001 should include at least the first file's migrations
    assert len(subset) <= len(all_migs)
    assert len(subset) > 0


def test_doris_migrations_have_dialect():
    for m in get_doris_migrations():
        assert m.dialect == "doris", f"Migration {m.version} should be doris dialect"


def test_every_migration_has_table_def():
    for mig in get_postgres_migrations():
        assert mig._table_def is not None, f"Missing _table_def for {mig.version}"
        assert mig._table_def.name, f"Missing table name for {mig.version}"
        assert len(mig._table_def.columns) > 0, f"No columns for {mig._table_def.name}"
