"""add durable financial connector operational events

Revision ID: 20260716_0022
Revises: 20260716_0021
Create Date: 2026-07-17 00:30:00
"""

from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "20260716_0022"
down_revision: str | None = "20260716_0021"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def _require_postgresql() -> None:
    dialect_name = op.get_bind().dialect.name
    if dialect_name != "postgresql":
        raise RuntimeError(
            "20260716_0022 only supports PostgreSQL; "
            f"refusing to mutate {dialect_name} without transactional constraint DDL"
        )


def _require_empty_operational_events_for_downgrade() -> None:
    count = int(
        op.get_bind().scalar(
            sa.text("SELECT COUNT(*) FROM financial_connector_operational_events")
        )
        or 0
    )
    if count:
        raise RuntimeError(
            "cannot downgrade financial connector operational events: "
            f"immutable operational facts exist (financial_connector_operational_events={count})"
        )


def upgrade() -> None:
    _require_postgresql()
    op.create_table(
        "financial_connector_operational_events",
        sa.Column("id", sa.String(length=36), nullable=False),
        sa.Column("tenant_id", sa.String(length=64), nullable=False),
        sa.Column("config_id", sa.String(length=36), nullable=False),
        sa.Column("provider", sa.String(length=80), nullable=False),
        sa.Column("environment", sa.String(length=16), nullable=False),
        sa.Column("event_type", sa.String(length=32), nullable=False),
        sa.Column("reason_code", sa.String(length=80), nullable=False),
        sa.Column("request_fingerprint", sa.String(length=76), nullable=False),
        sa.Column("external_event_fingerprint", sa.String(length=76), nullable=False),
        sa.Column("idempotency_key", sa.String(length=71), nullable=False),
        sa.Column(
            "occurred_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.func.now(),
        ),
        sa.CheckConstraint(
            "event_type IN ('replay', 'auth_failure', 'payload_conflict')",
            name="ck_financial_connector_operational_events_type",
        ),
        sa.CheckConstraint(
            "environment IN ('test', 'mock', 'staging', 'production')",
            name="ck_financial_connector_operational_events_environment",
        ),
        sa.CheckConstraint(
            "length(trim(provider)) > 0 AND length(trim(reason_code)) > 0",
            name="ck_financial_connector_operational_events_required_text",
        ),
        sa.CheckConstraint(
            "length(request_fingerprint) = 76 "
            "AND request_fingerprint LIKE 'hmac-sha256:%' "
            "AND length(external_event_fingerprint) = 76 "
            "AND external_event_fingerprint LIKE 'hmac-sha256:%' "
            "AND length(idempotency_key) = 71 "
            "AND idempotency_key LIKE 'sha256:%'",
            name="ck_financial_connector_operational_events_fingerprints",
        ),
        sa.ForeignKeyConstraint(
            ["tenant_id", "config_id"],
            ["financial_connector_configs.tenant_id", "financial_connector_configs.id"],
            name="fk_financial_connector_operational_events_tenant_config",
            ondelete="RESTRICT",
        ),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint(
            "tenant_id",
            "id",
            name="uq_financial_connector_operational_events_tenant_id",
        ),
        sa.UniqueConstraint(
            "tenant_id",
            "idempotency_key",
            name="uq_financial_connector_operational_events_tenant_request",
        ),
    )
    op.create_index(
        "ix_financial_connector_operational_events_tenant_config_time",
        "financial_connector_operational_events",
        ["tenant_id", "config_id", "occurred_at"],
    )
    op.create_index(
        "ix_financial_connector_operational_events_tenant_type_time",
        "financial_connector_operational_events",
        ["tenant_id", "event_type", "occurred_at"],
    )
    op.create_index(
        "ix_financial_connector_operational_events_tenant_provider_time",
        "financial_connector_operational_events",
        ["tenant_id", "provider", "occurred_at"],
    )
    op.execute(
        """
        CREATE TRIGGER trg_financial_connector_operational_events_append_only
        BEFORE UPDATE OR DELETE ON financial_connector_operational_events
        FOR EACH ROW EXECUTE FUNCTION reject_financial_connector_append_only_mutation()
        """
    )


def downgrade() -> None:
    _require_postgresql()
    _require_empty_operational_events_for_downgrade()
    op.execute(
        "DROP TRIGGER IF EXISTS "
        "trg_financial_connector_operational_events_append_only "
        "ON financial_connector_operational_events"
    )
    op.drop_index(
        "ix_financial_connector_operational_events_tenant_provider_time",
        table_name="financial_connector_operational_events",
    )
    op.drop_index(
        "ix_financial_connector_operational_events_tenant_type_time",
        table_name="financial_connector_operational_events",
    )
    op.drop_index(
        "ix_financial_connector_operational_events_tenant_config_time",
        table_name="financial_connector_operational_events",
    )
    op.drop_table("financial_connector_operational_events")
