"""promo code issuer fields

Revision ID: 052_promo_code_issuer
Revises: 051_auto_renew_events
Create Date: 2026-06-20
"""

import sqlalchemy as sa
from alembic import op


revision = "052_promo_code_issuer"
down_revision = "051_auto_renew_events"
branch_labels = None
depends_on = None


def _columns(bind, table_name: str) -> set[str]:
    return {column["name"] for column in sa.inspect(bind).get_columns(table_name)}


def upgrade() -> None:
    bind = op.get_bind()
    columns = _columns(bind, "promo_codes")

    if "issuer_user_id" not in columns:
        op.add_column("promo_codes", sa.Column("issuer_user_id", sa.BigInteger(), nullable=True))
        op.create_index("ix_promo_codes_issuer_user_id", "promo_codes", ["issuer_user_id"])
        op.create_foreign_key(
            "fk_promo_codes_issuer_user_id_users",
            "promo_codes",
            "users",
            ["issuer_user_id"],
            ["id"],
            ondelete="SET NULL",
        )
    if "issuer_type" not in columns:
        op.add_column("promo_codes", sa.Column("issuer_type", sa.String(length=16), nullable=True))
        op.create_index("ix_promo_codes_issuer_type", "promo_codes", ["issuer_type"])
    if "point_cost" not in columns:
        op.add_column("promo_codes", sa.Column("point_cost", sa.Integer(), nullable=False, server_default="0"))


def downgrade() -> None:
    bind = op.get_bind()
    columns = _columns(bind, "promo_codes")

    if "issuer_user_id" in columns:
        op.drop_constraint("fk_promo_codes_issuer_user_id_users", "promo_codes", type_="foreignkey")
        op.drop_index("ix_promo_codes_issuer_user_id", table_name="promo_codes")
        op.drop_column("promo_codes", "issuer_user_id")
    if "issuer_type" in columns:
        op.drop_index("ix_promo_codes_issuer_type", table_name="promo_codes")
        op.drop_column("promo_codes", "issuer_type")
    if "point_cost" in columns:
        op.drop_column("promo_codes", "point_cost")
