"""add minimum order amount and promo codes

Revision ID: 39b310f489be
Revises: ad2d93bd9512
Create Date: 2026-07-21 16:14:09.886212

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = "39b310f489be"
down_revision: Union[str, None] = "ad2d93bd9512"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # NOTE: autogenerate also proposed op.drop_table('spatial_ref_sys')
    # (a PostGIS system table — dropping it would break PostGIS
    # entirely) and dropping refresh_tokens_token_hash_key (recurring,
    # pre-existing unique-index-vs-named-constraint drift unrelated to
    # this migration — same drift called out in 42828b3f2eea). Both
    # removed by hand. orders.discount_amount gets a server_default of
    # 0.00 so existing orders backfill to "no discount applied" (true
    # for all of them — promo codes didn't exist before this
    # migration), then the default is dropped so only the Python-side
    # default applies going forward, same pattern as every other NOT
    # NULL column added in this project's history. The orders ->
    # promo_codes foreign key is named explicitly (autogenerate left
    # it anonymous), since an anonymous constraint can't be dropped by
    # name in downgrade().
    op.create_table(
        "promo_codes",
        sa.Column("id", sa.Uuid(), nullable=False),
        sa.Column("code", sa.String(length=30), nullable=False),
        sa.Column("merchant_id", sa.Uuid(), nullable=True),
        sa.Column("created_by_id", sa.Uuid(), nullable=False),
        sa.Column("discount_type", sa.String(length=20), nullable=False),
        sa.Column("discount_value", sa.Numeric(precision=10, scale=2), nullable=False),
        sa.Column(
            "max_discount_amount", sa.Numeric(precision=10, scale=2), nullable=True
        ),
        sa.Column("min_order_amount", sa.Numeric(precision=10, scale=2), nullable=True),
        sa.Column("usage_limit", sa.Integer(), nullable=True),
        sa.Column("usage_limit_per_customer", sa.Integer(), nullable=True),
        sa.Column("times_used", sa.Integer(), nullable=False),
        sa.Column("valid_from", sa.DateTime(), nullable=True),
        sa.Column("valid_until", sa.DateTime(), nullable=True),
        sa.Column("is_active", sa.Boolean(), nullable=False),
        sa.Column(
            "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False
        ),
        sa.Column(
            "updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False
        ),
        sa.ForeignKeyConstraint(
            ["created_by_id"],
            ["users.id"],
        ),
        sa.ForeignKeyConstraint(["merchant_id"], ["merchants.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_promo_codes_code"), "promo_codes", ["code"], unique=True)
    op.create_index(
        op.f("ix_promo_codes_merchant_id"), "promo_codes", ["merchant_id"], unique=False
    )
    op.create_table(
        "promo_code_redemptions",
        sa.Column("id", sa.Uuid(), nullable=False),
        sa.Column("promo_code_id", sa.Uuid(), nullable=False),
        sa.Column("customer_id", sa.Uuid(), nullable=False),
        sa.Column("order_id", sa.Uuid(), nullable=False),
        sa.Column("discount_amount", sa.Numeric(precision=10, scale=2), nullable=False),
        sa.Column(
            "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False
        ),
        sa.ForeignKeyConstraint(
            ["customer_id"],
            ["users.id"],
        ),
        sa.ForeignKeyConstraint(["order_id"], ["orders.id"], ondelete="CASCADE"),
        sa.ForeignKeyConstraint(
            ["promo_code_id"], ["promo_codes.id"], ondelete="CASCADE"
        ),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("order_id"),
    )
    op.create_index(
        op.f("ix_promo_code_redemptions_customer_id"),
        "promo_code_redemptions",
        ["customer_id"],
        unique=False,
    )
    op.create_index(
        op.f("ix_promo_code_redemptions_promo_code_id"),
        "promo_code_redemptions",
        ["promo_code_id"],
        unique=False,
    )
    op.add_column(
        "branches",
        sa.Column(
            "minimum_order_amount", sa.Numeric(precision=10, scale=2), nullable=True
        ),
    )
    op.add_column(
        "orders",
        sa.Column(
            "discount_amount",
            sa.Numeric(precision=10, scale=2),
            nullable=False,
            server_default="0.00",
        ),
    )
    op.alter_column("orders", "discount_amount", server_default=None)
    op.add_column("orders", sa.Column("promo_code_id", sa.Uuid(), nullable=True))
    op.create_foreign_key(
        "fk_orders_promo_code_id_promo_codes",
        "orders",
        "promo_codes",
        ["promo_code_id"],
        ["id"],
    )


def downgrade() -> None:
    op.drop_constraint(
        "fk_orders_promo_code_id_promo_codes", "orders", type_="foreignkey"
    )
    op.drop_column("orders", "promo_code_id")
    op.drop_column("orders", "discount_amount")
    op.drop_column("branches", "minimum_order_amount")
    op.drop_index(
        op.f("ix_promo_code_redemptions_promo_code_id"),
        table_name="promo_code_redemptions",
    )
    op.drop_index(
        op.f("ix_promo_code_redemptions_customer_id"),
        table_name="promo_code_redemptions",
    )
    op.drop_table("promo_code_redemptions")
    op.drop_index(op.f("ix_promo_codes_merchant_id"), table_name="promo_codes")
    op.drop_index(op.f("ix_promo_codes_code"), table_name="promo_codes")
    op.drop_table("promo_codes")
    # ### end Alembic commands ###
