import os
from pathlib import Path

from alembic import command
from alembic.config import Config
from sqlmodel import SQLModel

from activemodel.session_manager import get_engine
from sqlalchemy import inspect


def test_migrations():
    # all of the tables should be loaded into the SQLModel metadata before running alembic
    assert len(SQLModel.metadata.tables) >= 4

    # if we create the tables before running alembic, it won't be picked up
    inspector = inspect(get_engine())
    assert not inspector.get_table_names(), "Expected no tables in the DB."

    test_root = Path(__file__).parent
    migrations_path = test_root / "migrations"
    versions_path = migrations_path / "versions"

    # remove all existing migration files
    for file in os.listdir(str(versions_path)):
        os.remove(str(versions_path / file))

    # Configure Alembic
    alembic_cfg = Config(str(migrations_path / "alembic.ini"))
    alembic_cfg.set_main_option("script_location", str(test_root / "migrations"))

    # Generate a revision with autogenerate enabled
    command.revision(alembic_cfg, message="autogenerated migration", autogenerate=True)

    # Inspect the migration file if needed
    migration_files = [f for f in os.listdir(str(versions_path)) if f.endswith(".py")]
    migration_path = os.path.join(str(versions_path), sorted(migration_files)[-1])

    with open(migration_path, "r") as f:
        migration_contents = f.read()

    # ensure that the computed properties exist
    assert "op.create_table('example_with_id'" in migration_contents
    assert "op.f('example_with_id_example_record_id_fkey'))" in migration_contents
    assert "name=op.f('example_with_id_another_example_id_fkey'))" in migration_contents
