"""stripe_events: UUID id PK, payload JSONB (match ORM).

Revision ID: 069
Revises: 068

001 created stripe_events with stripe_event_id as sole PK and no id/payload columns.
The StripeEvent model expects id (UUID PK), stripe_event_id (unique), and payload.
Production webhooks fail with UndefinedColumn on stripe_events.id until this runs.
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy import inspect
from sqlalchemy.dialects import postgresql

revision = "069"
down_revision = "068"
branch_labels = None
depends_on = None


def upgrade() -> None:
    conn = op.get_bind()
    insp = inspect(conn)
    cols = {c["name"] for c in insp.get_columns("stripe_events")}
    if "id" in cols:
        return

    op.add_column(
        "stripe_events",
        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            nullable=False,
            server_default=sa.text("gen_random_uuid()"),
        ),
    )
    op.add_column("stripe_events", sa.Column("payload", postgresql.JSONB(), nullable=True))

    op.drop_constraint("stripe_events_pkey", "stripe_events", type_="primary")
    op.create_primary_key("stripe_events_pkey", "stripe_events", ["id"])
    op.create_unique_constraint(
        "uq_stripe_events_stripe_event_id",
        "stripe_events",
        ["stripe_event_id"],
    )

    op.alter_column(
        "stripe_events",
        "id",
        server_default=None,
    )


def downgrade() -> None:
    conn = op.get_bind()
    insp = inspect(conn)
    cols = {c["name"] for c in insp.get_columns("stripe_events")}
    if "id" not in cols:
        return

    op.drop_constraint("uq_stripe_events_stripe_event_id", "stripe_events", type_="unique")
    op.drop_constraint("stripe_events_pkey", "stripe_events", type_="primary")
    op.create_primary_key("stripe_events_pkey", "stripe_events", ["stripe_event_id"])
    op.drop_column("stripe_events", "payload")
    op.drop_column("stripe_events", "id")
