"""add coupon_activity_claims table

Revision ID: 076_coupon_activity_claims
Revises: 075_admin_impersonation_audits
Create Date: 2026-07-11
"""

import sqlalchemy as sa
from alembic import op


revision = "076_coupon_activity_claims"
down_revision = "075_admin_impersonation_audits"
branch_labels = None
depends_on = None


def upgrade() -> None:
    bind = op.get_bind()
    if "coupon_activity_claims" in set(sa.inspect(bind).get_table_names()):
        return
    op.create_table(
        "coupon_activity_claims",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("promo_code_id", sa.Integer(), nullable=False),
        sa.Column("user_id", sa.BigInteger(), nullable=False),
        sa.Column("activity_id", sa.Integer(), nullable=True),
        sa.Column(
            "status",
            sa.Enum("claimed", "used", "expired", name="couponactivityclaimstatus"),
            nullable=False,
            server_default="claimed",
        ),
        sa.Column("used_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("order_id", sa.Integer(), nullable=True),
        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.ForeignKeyConstraint(["promo_code_id"], ["promo_codes.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["order_id"], ["orders.id"], ondelete="SET NULL"),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index("ix_coupon_activity_claims_promo_code_id", "coupon_activity_claims", ["promo_code_id"])
    op.create_index("ix_coupon_activity_claims_user_id", "coupon_activity_claims", ["user_id"])
    op.create_index("ix_coupon_activity_claims_activity_id", "coupon_activity_claims", ["activity_id"])
    op.create_index("ix_coupon_activity_claims_status", "coupon_activity_claims", ["status"])
    op.create_index("ix_coupon_activity_claims_order_id", "coupon_activity_claims", ["order_id"])


def downgrade() -> None:
    bind = op.get_bind()
    if "coupon_activity_claims" in set(sa.inspect(bind).get_table_names()):
        op.drop_table("coupon_activity_claims")
    # drop enum type for postgres
    try:
        op.execute("DROP TYPE IF EXISTS couponactivityclaimstatus")
    except Exception:
        pass
