from alembic import context

from xmas_app.models.orm import Base

config = context.config

target_metadata = Base.metadata


def run_migrations_offline():
    context.configure(
        url=None,
        target_metadata=target_metadata,
        literal_binds=True,
        compare_type=True,
        version_table="xmas_app_revision",
    )
    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online():
    connection = config.attributes.get("connection")
    if connection is not None:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            version_table="xmas_app_revision",
        )
        with context.begin_transaction():
            context.run_migrations()
    else:
        from xmas_app.settings import get_settings

        repo = get_settings().repo
        config.attributes["schema"] = repo.schema or "public"
        with repo._engine.connect() as connection:
            context.configure(
                connection=connection,
                target_metadata=target_metadata,
                version_table="xmas_app_revision",
            )
            with context.begin_transaction():
                context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
