"""Verify the campaign analysis-model migration adds a nullable column."""

import importlib

import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations


def test_campaign_analysis_model_migration_adds_nullable_column(tmp_path, monkeypatch):
    engine = sa.create_engine(f"sqlite:///{tmp_path / 'campaign_analysis.db'}")
    metadata = sa.MetaData()
    legacy_table = sa.Table(
        "campaigns",
        metadata,
        sa.Column("id", sa.String(), primary_key=True),
        sa.Column("name", sa.String(), nullable=False),
    )
    metadata.create_all(engine)

    with engine.begin() as connection:
        connection.execute(legacy_table.insert().values(id="camp-1", name="现有活动"))
        operations = Operations(MigrationContext.configure(connection))
        migration = importlib.import_module(
            "migrations.versions.b7e4d3a92c15_add_campaign_analysis_model"
        )
        monkeypatch.setattr(migration, "op", operations)
        migration.upgrade()

        columns = {c["name"]: c for c in sa.inspect(connection).get_columns("campaigns")}
        assert "analysis_model_config_id" in columns
        assert columns["analysis_model_config_id"]["nullable"] is True

        value = connection.execute(
            sa.text("SELECT analysis_model_config_id FROM campaigns WHERE id = :id"),
            {"id": "camp-1"},
        ).scalar_one()
        assert value is None
