"""add gift card tables and shop settings

Revision ID: f8201a9ba045
Revises: 6b516114c393
Create Date: 2026-03-07 15:09:21.421155

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'f8201a9ba045'
down_revision = '6b516114c393'
branch_labels = None
depends_on = None

from make_post_sell.models.meta import UUIDType


def _table_exists(name):
    conn = op.get_bind()
    result = conn.execute(
        sa.text("SELECT name FROM sqlite_master WHERE type='table' AND name=:name"),
        {"name": name},
    )
    return result.fetchone() is not None


def _column_exists(table, column):
    conn = op.get_bind()
    result = conn.execute(sa.text(f"PRAGMA table_info({table})"))
    return any(row[1] == column for row in result.fetchall())


def upgrade():
    # Gift card table
    if not _table_exists("mps_gift_card"):
        op.create_table(
            "mps_gift_card",
            sa.Column("id", UUIDType, primary_key=True),
            sa.Column("shop_id", UUIDType, sa.ForeignKey("mps_shop.id"), nullable=False),
            sa.Column("code", sa.Unicode(64), nullable=False, unique=True),
            sa.Column("initial_amount_in_cents", sa.BigInteger(), nullable=False),
            sa.Column("balance_in_cents", sa.BigInteger(), nullable=False),
            sa.Column("purchaser_email", sa.Unicode(256), nullable=True),
            sa.Column("gift_email", sa.Unicode(256), nullable=True),
            sa.Column("gift_message", sa.Unicode(512), nullable=True),
            sa.Column("invoice_id", UUIDType, sa.ForeignKey("mps_invoice.id"), nullable=True),
            sa.Column("created_timestamp", sa.BigInteger(), nullable=False),
            sa.Column("disabled", sa.Boolean(), nullable=False, server_default="0"),
        )
        op.create_index("ix_mps_gift_card_code", "mps_gift_card", ["code"])
        op.create_index("ix_mps_gift_card_shop_id", "mps_gift_card", ["shop_id"])

    # Gift card transaction table
    if not _table_exists("mps_gift_card_transaction"):
        op.create_table(
            "mps_gift_card_transaction",
            sa.Column("id", UUIDType, primary_key=True),
            sa.Column("gift_card_id", UUIDType, sa.ForeignKey("mps_gift_card.id"), nullable=False),
            sa.Column("invoice_id", UUIDType, sa.ForeignKey("mps_invoice.id"), nullable=False),
            sa.Column("amount_in_cents", sa.BigInteger(), nullable=False),
            sa.Column("created_timestamp", sa.BigInteger(), nullable=False),
        )

    # Cart-to-gift-card association table
    if not _table_exists("mps_cart_gift_card"):
        op.create_table(
            "mps_cart_gift_card",
            sa.Column("id", UUIDType, primary_key=True),
            sa.Column("cart_id", UUIDType, sa.ForeignKey("mps_cart.id"), nullable=False),
            sa.Column("gift_card_id", UUIDType, sa.ForeignKey("mps_gift_card.id"), nullable=False),
            sa.Column("created_timestamp", sa.BigInteger(), nullable=False),
        )

    # Cart gift card purchase items column
    if not _column_exists("mps_cart", "json_gift_cards"):
        op.add_column(
            "mps_cart",
            sa.Column("json_gift_cards", sa.UnicodeText(), nullable=True, server_default="[]"),
        )

    # Shop gift card settings
    if not _column_exists("mps_shop", "gift_card_enabled"):
        op.add_column(
            "mps_shop",
            sa.Column("gift_card_enabled", sa.Boolean(), nullable=False, server_default="0"),
        )
    if not _column_exists("mps_shop", "gift_card_min_in_cents"):
        op.add_column(
            "mps_shop",
            sa.Column("gift_card_min_in_cents", sa.BigInteger(), nullable=False, server_default="500"),
        )
    if not _column_exists("mps_shop", "gift_card_max_in_cents"):
        op.add_column(
            "mps_shop",
            sa.Column("gift_card_max_in_cents", sa.BigInteger(), nullable=False, server_default="25000"),
        )


def downgrade():
    if _table_exists("mps_cart_gift_card"):
        op.drop_table("mps_cart_gift_card")
    if _table_exists("mps_gift_card_transaction"):
        op.drop_table("mps_gift_card_transaction")
    if _table_exists("mps_gift_card"):
        op.drop_table("mps_gift_card")
    if _column_exists("mps_cart", "json_gift_cards"):
        op.drop_column("mps_cart", "json_gift_cards")
    if _column_exists("mps_shop", "gift_card_enabled"):
        op.drop_column("mps_shop", "gift_card_enabled")
    if _column_exists("mps_shop", "gift_card_min_in_cents"):
        op.drop_column("mps_shop", "gift_card_min_in_cents")
    if _column_exists("mps_shop", "gift_card_max_in_cents"):
        op.drop_column("mps_shop", "gift_card_max_in_cents")
