"""add write idempotency keys

Revision ID: e9f0a1b2c3d4
Revises: d8e9f0a1b2c3
Create Date: 2026-06-23

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB, UUID

revision = "e9f0a1b2c3d4"
down_revision = "d8e9f0a1b2c3"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "write_idempotency_keys",
        sa.Column("id", UUID(as_uuid=True), primary_key=True),
        sa.Column("key", sa.String(length=200), nullable=False),
        sa.Column("method", sa.String(length=10), nullable=False),
        sa.Column("path", sa.Text(), nullable=False),
        sa.Column("route_class", sa.String(length=30), nullable=False),
        sa.Column("request_hash", sa.String(length=64), nullable=False),
        sa.Column("response_status", sa.Integer(), nullable=False),
        sa.Column("response_body", JSONB(), nullable=True),
        sa.Column("source_host", sa.String(length=200), nullable=True),
        sa.Column("source_agent", sa.String(length=100), nullable=True),
        sa.Column("first_seen_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("last_seen_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True),
        sa.UniqueConstraint("key", name="uq_write_idempotency_keys_key"),
    )
    op.create_index("ix_write_idempotency_keys_key", "write_idempotency_keys", ["key"])
    op.create_index("ix_write_idempotency_keys_expires_at", "write_idempotency_keys", ["expires_at"])


def downgrade() -> None:
    op.drop_index("ix_write_idempotency_keys_expires_at", table_name="write_idempotency_keys")
    op.drop_index("ix_write_idempotency_keys_key", table_name="write_idempotency_keys")
    op.drop_table("write_idempotency_keys")
