"""add promo code usage ledger

Revision ID: 045_promo_code_usage
Revises: 044_more_system_settings
Create Date: 2026-06-19
"""

import sqlalchemy as sa
from alembic import op


revision = "045_promo_code_usage"
down_revision = "044_more_system_settings"
branch_labels = None
depends_on = None


def _table_names(bind) -> set[str]:
    return set(sa.inspect(bind).get_table_names())


def upgrade() -> None:
    bind = op.get_bind()
    if "promo_code_usages" in _table_names(bind):
        return

    op.create_table(
        "promo_code_usages",
        sa.Column("promo_code_id", sa.Integer(), nullable=False),
        sa.Column("code_snapshot", sa.String(length=64), nullable=False),
        sa.Column("user_id", sa.BigInteger(), nullable=False),
        sa.Column("order_id", sa.Integer(), nullable=False),
        sa.Column("order_amount", sa.Integer(), nullable=False, server_default=sa.text("0")),
        sa.Column("eligible_amount", sa.Integer(), nullable=False, server_default=sa.text("0")),
        sa.Column("discount_amount", sa.Integer(), nullable=False, server_default=sa.text("0")),
        sa.Column("status", sa.String(length=24), nullable=False, server_default=sa.text("'used'")),
        sa.Column("used_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("payload_snapshot", sa.JSON(), nullable=True),
        sa.Column("id", sa.Integer(), autoincrement=True, 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.ForeignKeyConstraint(["order_id"], ["orders.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["promo_code_id"], ["promo_codes.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("order_id", name="uq_promo_code_usages_order_id"),
    )
    op.create_index("ix_promo_code_usages_promo_code_id", "promo_code_usages", ["promo_code_id"])
    op.create_index("ix_promo_code_usages_code_snapshot", "promo_code_usages", ["code_snapshot"])
    op.create_index("ix_promo_code_usages_user_id", "promo_code_usages", ["user_id"])
    op.create_index("ix_promo_code_usages_order_id", "promo_code_usages", ["order_id"])
    op.create_index("ix_promo_code_usages_status", "promo_code_usages", ["status"])


def downgrade() -> None:
    bind = op.get_bind()
    if "promo_code_usages" not in _table_names(bind):
        return
    op.drop_table("promo_code_usages")
