"""add expense case and transactional business event tables

This is the first migration-owned schema slice in a legacy database that still
bootstraps older tables through SQLAlchemy metadata. The server startup runs
this revision before the legacy bootstrap, and the legacy bootstrap explicitly
excludes these migration-owned tables.

Revision ID: 20260713_0001
Revises:
Create Date: 2026-07-13 11:45:00
"""

from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "20260713_0001"
down_revision: str | None = None
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    op.create_table(
        "expense_cases",
        sa.Column("id", sa.String(length=36), nullable=False),
        sa.Column("tenant_id", sa.String(length=64), nullable=False),
        sa.Column("case_no", sa.String(length=80), nullable=False),
        sa.Column("scene_code", sa.String(length=50), nullable=False),
        sa.Column("title", sa.String(length=200), nullable=False),
        sa.Column("owner_employee_id", sa.String(length=36), nullable=True),
        sa.Column("current_stage", sa.String(length=40), nullable=False),
        sa.Column("status", sa.String(length=30), nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("tenant_id", "case_no", name="uq_expense_cases_tenant_case_no"),
    )
    op.create_index("ix_expense_cases_tenant_id", "expense_cases", ["tenant_id"])
    op.create_index("ix_expense_cases_owner_employee_id", "expense_cases", ["owner_employee_id"])
    op.create_index(
        "ix_expense_cases_tenant_stage",
        "expense_cases",
        ["tenant_id", "current_stage"],
    )
    op.create_index(
        "ix_expense_cases_tenant_status",
        "expense_cases",
        ["tenant_id", "status"],
    )

    op.create_table(
        "expense_case_links",
        sa.Column("id", sa.String(length=36), nullable=False),
        sa.Column("tenant_id", sa.String(length=64), nullable=False),
        sa.Column("expense_case_id", sa.String(length=36), nullable=False),
        sa.Column("resource_type", sa.String(length=50), nullable=False),
        sa.Column("resource_id", sa.String(length=100), nullable=False),
        sa.Column("relation_type", sa.String(length=50), nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
        sa.ForeignKeyConstraint(["expense_case_id"], ["expense_cases.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("resource_type", "resource_id", name="uq_expense_case_links_resource"),
    )
    op.create_index("ix_expense_case_links_tenant_id", "expense_case_links", ["tenant_id"])
    op.create_index(
        "ix_expense_case_links_tenant_case",
        "expense_case_links",
        ["tenant_id", "expense_case_id"],
    )

    op.create_table(
        "business_events",
        sa.Column("id", sa.String(length=36), nullable=False),
        sa.Column("tenant_id", sa.String(length=64), nullable=False),
        sa.Column("expense_case_id", sa.String(length=36), nullable=False),
        sa.Column("aggregate_type", sa.String(length=50), nullable=False),
        sa.Column("aggregate_id", sa.String(length=100), nullable=False),
        sa.Column("event_type", sa.String(length=80), nullable=False),
        sa.Column("event_version", sa.Integer(), nullable=False),
        sa.Column("idempotency_key", sa.String(length=120), nullable=False),
        sa.Column("correlation_id", sa.String(length=64), nullable=False),
        sa.Column("causation_id", sa.String(length=64), nullable=True),
        sa.Column("actor_id", sa.String(length=120), nullable=False),
        sa.Column("actor_type", sa.String(length=30), nullable=False),
        sa.Column("payload_json", sa.JSON(), nullable=False),
        sa.Column("delivery_status", sa.String(length=20), nullable=False),
        sa.Column("delivery_attempts", sa.Integer(), nullable=False),
        sa.Column("last_delivery_error", sa.Text(), nullable=True),
        sa.Column(
            "occurred_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
        sa.Column("published_at", sa.DateTime(timezone=True), nullable=True),
        sa.ForeignKeyConstraint(["expense_case_id"], ["expense_cases.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint(
            "tenant_id",
            "aggregate_type",
            "aggregate_id",
            "event_type",
            "idempotency_key",
            name="uq_business_event_idempotency",
        ),
    )
    op.create_index("ix_business_events_tenant_id", "business_events", ["tenant_id"])
    op.create_index("ix_business_events_event_type", "business_events", ["event_type"])
    op.create_index("ix_business_events_correlation_id", "business_events", ["correlation_id"])
    op.create_index(
        "ix_business_events_tenant_case_time",
        "business_events",
        ["tenant_id", "expense_case_id", "occurred_at"],
    )
    op.create_index(
        "ix_business_events_outbox",
        "business_events",
        ["delivery_status", "occurred_at"],
    )
    op.create_index(
        "ix_business_events_aggregate",
        "business_events",
        ["aggregate_type", "aggregate_id"],
    )


def downgrade() -> None:
    op.drop_index("ix_business_events_aggregate", table_name="business_events")
    op.drop_index("ix_business_events_outbox", table_name="business_events")
    op.drop_index("ix_business_events_tenant_case_time", table_name="business_events")
    op.drop_index("ix_business_events_correlation_id", table_name="business_events")
    op.drop_index("ix_business_events_event_type", table_name="business_events")
    op.drop_index("ix_business_events_tenant_id", table_name="business_events")
    op.drop_table("business_events")

    op.drop_index("ix_expense_case_links_tenant_case", table_name="expense_case_links")
    op.drop_index("ix_expense_case_links_tenant_id", table_name="expense_case_links")
    op.drop_table("expense_case_links")

    op.drop_index("ix_expense_cases_tenant_status", table_name="expense_cases")
    op.drop_index("ix_expense_cases_tenant_stage", table_name="expense_cases")
    op.drop_index("ix_expense_cases_owner_employee_id", table_name="expense_cases")
    op.drop_index("ix_expense_cases_tenant_id", table_name="expense_cases")
    op.drop_table("expense_cases")
