"""Fix order_line unique constraints to include variant_id

The old constraints (order_id, product_id) caused 409 errors when
multiple variants of the same product were added to the same order.
New constraints use COALESCE(variant_id, nil_uuid) so different
variants of the same product can coexist.

Revision ID: 023
Revises: 022
Create Date: 2026-03-03
"""
from alembic import op

revision = "023"
down_revision = "022"
branch_labels = None
depends_on = None

NIL_UUID = "00000000-0000-0000-0000-000000000000"


def upgrade() -> None:
    # Drop old constraints
    op.execute("DROP INDEX IF EXISTS uq_order_lines_tracking")
    op.execute("DROP INDEX IF EXISTS uq_order_lines_render")

    # Recreate with variant_id included (COALESCE handles NULLs)
    op.execute(
        "CREATE UNIQUE INDEX uq_order_lines_tracking "
        f"ON order_lines (order_id, product_id, COALESCE(variant_id, '{NIL_UUID}'::uuid)) "
        "WHERE output_type_id IS NULL"
    )
    op.execute(
        "CREATE UNIQUE INDEX uq_order_lines_render "
        "ON order_lines (order_id, product_id, output_type_id, "
        f"COALESCE(variant_id, '{NIL_UUID}'::uuid)) "
        "WHERE output_type_id IS NOT NULL"
    )


def downgrade() -> None:
    op.execute("DROP INDEX IF EXISTS uq_order_lines_tracking")
    op.execute("DROP INDEX IF EXISTS uq_order_lines_render")

    # Restore original constraints without variant_id
    op.execute(
        "CREATE UNIQUE INDEX uq_order_lines_tracking "
        "ON order_lines (order_id, product_id) "
        "WHERE output_type_id IS NULL"
    )
    op.execute(
        "CREATE UNIQUE INDEX uq_order_lines_render "
        "ON order_lines (order_id, product_id, output_type_id) "
        "WHERE output_type_id IS NOT NULL"
    )
