"""Phase 7.3 — Rewards Engine (reward redemptions)."""
from alembic import op
import sqlalchemy as sa

revision = "0004_phase_73_rewards"
down_revision = "0003_phase_72_points"
branch_labels = None
depends_on = None


def upgrade():
    op.add_column("rewards", sa.Column("stock_limit", sa.Integer(), nullable=True))
    op.add_column(
        "rewards",
        sa.Column(
            "redeemed_count", sa.Integer(), nullable=False, server_default="0"
        ),
    )
    op.add_column("rewards", sa.Column("max_per_member", sa.Integer(), nullable=True))

    op.create_table(
        "reward_redemptions",
        sa.Column("id", sa.CHAR(length=36), primary_key=True),
        sa.Column("tenant_id", sa.CHAR(length=36), nullable=False),
        sa.Column("program_id", sa.CHAR(length=36), nullable=False),
        sa.Column("reward_id", sa.CHAR(length=36), nullable=False),
        sa.Column("member_id", sa.CHAR(length=36), nullable=False),
        sa.Column("point_account_id", sa.CHAR(length=36), nullable=False),
        sa.Column("status", sa.String(length=20), nullable=False),
        sa.Column("points_spent", sa.Integer(), nullable=False),
        sa.Column("ledger_entry_id", sa.CHAR(length=36), nullable=True),
        sa.Column("voucher_code", sa.String(length=50), nullable=False),
        sa.Column("idempotency_key", sa.String(length=100), nullable=True),
        sa.Column("reason", sa.String(length=500), nullable=True),
        sa.Column("cancel_reason", sa.String(length=500), nullable=True),
        sa.Column("fulfilled_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("cancelled_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("metadata_json", sa.JSON(), nullable=True),
        sa.Column("actor_user_id", sa.String(length=100), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
        sa.UniqueConstraint(
            "tenant_id",
            "idempotency_key",
            name="uq_reward_redemptions_tenant_idempotency",
        ),
    )
    op.create_index(
        "ix_reward_redemptions_reward",
        "reward_redemptions",
        ["tenant_id", "reward_id"],
    )
    op.create_index(
        "ix_reward_redemptions_member",
        "reward_redemptions",
        ["tenant_id", "member_id"],
    )
    op.create_index(
        "ix_reward_redemptions_status",
        "reward_redemptions",
        ["tenant_id", "status"],
    )


def downgrade():
    op.drop_index("ix_reward_redemptions_status", table_name="reward_redemptions")
    op.drop_index("ix_reward_redemptions_member", table_name="reward_redemptions")
    op.drop_index("ix_reward_redemptions_reward", table_name="reward_redemptions")
    op.drop_table("reward_redemptions")
    op.drop_column("rewards", "max_per_member")
    op.drop_column("rewards", "redeemed_count")
    op.drop_column("rewards", "stock_limit")
