"""Add channel SKU prefix mapping (master prefix → channel prefix).

Revision ID: 0035_add_channel_sku_prefix_mapping
Revises: 0034_add_channel_sku_mapping_connection_id
Create Date: 2026-06-12 23:30:00.000000
"""

from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "0035_add_channel_sku_prefix_mapping"
down_revision = "0034_add_channel_sku_mapping_connection_id"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "channel_sku_prefix_mapping",
        sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
        sa.Column("channel_code", sa.String(32), nullable=False),
        sa.Column("connection_id", sa.Integer(), nullable=True),
        sa.Column("master_prefix", sa.String(64), nullable=False),
        sa.Column("channel_prefix", sa.String(64), nullable=False),
        sa.Column("mapping_status", sa.String(32), nullable=False, server_default="active"),
        sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("notes", sa.Text(), nullable=True),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.func.now(),
        ),
        sa.UniqueConstraint(
            "channel_code",
            "master_prefix",
            name="uq_channel_sku_prefix_channel_master",
        ),
    )
    op.create_index("ix_channel_sku_prefix_mapping_channel_code", "channel_sku_prefix_mapping", ["channel_code"])
    op.create_index("ix_channel_sku_prefix_mapping_connection_id", "channel_sku_prefix_mapping", ["connection_id"])
    op.create_index("ix_channel_sku_prefix_mapping_master_prefix", "channel_sku_prefix_mapping", ["master_prefix"])
    op.create_index(
        "uq_channel_sku_prefix_master_connection",
        "channel_sku_prefix_mapping",
        ["master_prefix", "connection_id"],
        unique=True,
        postgresql_where=sa.text("connection_id IS NOT NULL"),
    )


def downgrade() -> None:
    op.drop_index("uq_channel_sku_prefix_master_connection", table_name="channel_sku_prefix_mapping")
    op.drop_index("ix_channel_sku_prefix_mapping_master_prefix", table_name="channel_sku_prefix_mapping")
    op.drop_index("ix_channel_sku_prefix_mapping_connection_id", table_name="channel_sku_prefix_mapping")
    op.drop_index("ix_channel_sku_prefix_mapping_channel_code", table_name="channel_sku_prefix_mapping")
    op.drop_table("channel_sku_prefix_mapping")
