"""loyalty 007 - add transaction categories

Adds store-scoped product categories (e.g., Men, Women, Accessories)
that sellers select when entering loyalty transactions. Also adds
category_id FK on loyalty_transactions.

Revision ID: loyalty_007
Revises: loyalty_006
Create Date: 2026-04-19
"""
import sqlalchemy as sa

from alembic import op

revision = "loyalty_007"
down_revision = "loyalty_006"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "store_transaction_categories",
        sa.Column("id", sa.Integer(), primary_key=True, index=True),
        sa.Column(
            "store_id",
            sa.Integer(),
            sa.ForeignKey("stores.id"),
            nullable=False,
        ),
        sa.Column("name", sa.String(100), nullable=False),
        sa.Column("display_order", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.UniqueConstraint("store_id", "name", name="uq_store_category_name"),
    )
    op.create_index(
        "idx_store_category_store",
        "store_transaction_categories",
        ["store_id", "is_active"],
    )

    op.add_column(
        "loyalty_transactions",
        sa.Column(
            "category_id",
            sa.Integer(),
            sa.ForeignKey("store_transaction_categories.id", ondelete="SET NULL"),
            nullable=True,
        ),
    )


def downgrade() -> None:
    op.drop_column("loyalty_transactions", "category_id")
    op.drop_index("idx_store_category_store", table_name="store_transaction_categories")
    op.drop_table("store_transaction_categories")
