from sqlalchemy import create_engine, inspect

from scripts.docker_entrypoint import HEAD_REVISION, INITIAL_REVISION, current_revision, run_migrations


def test_run_migrations_on_empty_sqlite(tmp_path, monkeypatch):
    db_path = tmp_path / "migrate.sqlite"
    database_url = f"sqlite+pysqlite:///{db_path.as_posix()}"
    monkeypatch.setenv("DATABASE_URL", database_url)

    from app.core.config import settings

    monkeypatch.setattr(settings, "database_url", database_url)

    engine = create_engine(database_url)
    run_migrations(engine)

    tables = set(inspect(engine).get_table_names())
    assert "users" in tables
    assert current_revision(engine) == HEAD_REVISION


def test_run_migrations_stamps_existing_schema_without_alembic(tmp_path, monkeypatch):
    db_path = tmp_path / "existing.sqlite"
    database_url = f"sqlite+pysqlite:///{db_path.as_posix()}"
    monkeypatch.setenv("DATABASE_URL", database_url)

    from app.core.config import settings

    monkeypatch.setattr(settings, "database_url", database_url)

    engine = create_engine(database_url)
    with engine.begin() as connection:
        connection.exec_driver_sql(
            """
            CREATE TABLE users (
                id VARCHAR(36) PRIMARY KEY,
                email VARCHAR(255) NOT NULL UNIQUE,
                password_hash VARCHAR(255) NOT NULL,
                role VARCHAR(16) NOT NULL,
                status VARCHAR(16) NOT NULL,
                failed_login_attempts INTEGER NOT NULL,
                locked_until TIMESTAMP,
                email_verified_at TIMESTAMP,
                created_at TIMESTAMP NOT NULL,
                updated_at TIMESTAMP NOT NULL
            )
            """
        )

    run_migrations(engine)

    tables = set(inspect(engine).get_table_names())
    assert "refresh_tokens" in tables
    assert current_revision(engine) == HEAD_REVISION
    assert INITIAL_REVISION == "20260711_0001"


def test_run_migrations_repairs_partial_schema_with_stale_alembic(tmp_path, monkeypatch):
    db_path = tmp_path / "stale.sqlite"
    database_url = f"sqlite+pysqlite:///{db_path.as_posix()}"
    monkeypatch.setenv("DATABASE_URL", database_url)

    from app.core.config import settings

    monkeypatch.setattr(settings, "database_url", database_url)

    engine = create_engine(database_url)
    with engine.begin() as connection:
        connection.exec_driver_sql(
            """
            CREATE TABLE users (
                id VARCHAR(36) PRIMARY KEY,
                email VARCHAR(255) NOT NULL UNIQUE,
                password_hash VARCHAR(255) NOT NULL,
                role VARCHAR(16) NOT NULL,
                status VARCHAR(16) NOT NULL,
                failed_login_attempts INTEGER NOT NULL,
                locked_until TIMESTAMP,
                email_verified_at TIMESTAMP,
                created_at TIMESTAMP NOT NULL,
                updated_at TIMESTAMP NOT NULL
            )
            """
        )
        connection.exec_driver_sql(
            """
            CREATE TABLE alembic_version (
                version_num VARCHAR(32) NOT NULL PRIMARY KEY
            )
            """
        )
        connection.exec_driver_sql(
            f"INSERT INTO alembic_version (version_num) VALUES ('{INITIAL_REVISION}')"
        )

    run_migrations(engine)

    tables = set(inspect(engine).get_table_names())
    assert "refresh_tokens" in tables
    assert current_revision(engine) == HEAD_REVISION
