from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
MIGRATION = (
    ROOT
    / "migrations"
    / "versions"
    / "20260718_60_workflow_engine_abstraction.py"
)


def test_engine_abstraction_migration_preserves_n8n_and_adds_generic_tables():
    migration = MIGRATION.read_text(encoding="utf-8")

    assert 'revision = "20260718_60"' in migration
    assert 'down_revision = "20260718_50"' in migration
    assert "engine_type" in migration
    assert "engine_definition_id" in migration
    assert "engine_revision" in migration
    assert "deployment_metadata" in migration
    assert "workflow_spec" in migration
    assert "schedule_plan" in migration
    assert "UPDATE public.dataflow_workflow_versions" in migration
    assert "n8n_workflow_id" in migration

    for table in (
        "workflow_schedules",
        "workflow_runs",
        "workflow_task_runs",
        "workflow_engine_bindings",
        "workflow_plan_audits",
    ):
        assert table in migration


def test_database_enforces_one_enabled_primary_engine_per_dataflow_environment():
    migration = MIGRATION.read_text(encoding="utf-8")

    assert "uq_workflow_engine_primary_environment" in migration
    assert "WHERE role = 'primary' AND status = 'enabled'" in migration
    assert "uq_workflow_engine_shadow_environment" in migration


def test_v50_migration_has_an_explicit_rollback():
    migration = MIGRATION.read_text(encoding="utf-8")
    downgrade = migration.split("def downgrade() -> None:", 1)[1]

    assert "DROP TABLE IF EXISTS public.workflow_plan_audits" in downgrade
    assert "DROP COLUMN IF EXISTS engine_type" in downgrade
