"""Fix currency unique constraint — tenant-scoped instead of global.

Revision ID: 0014_currency_unique_fix
Revises: 0013_addresses
Create Date: 2026-07-04
"""

from __future__ import annotations

from typing import Sequence, Union

from alembic import op

revision: str = "0014_currency_unique_fix"
down_revision: Union[str, None] = "0013_addresses"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Drop the old global unique constraint on currencies.code
    op.execute("ALTER TABLE currencies DROP CONSTRAINT IF EXISTS currencies_code_key")
    op.execute("DROP INDEX IF EXISTS currencies_code_key")

    # Add tenant-scoped unique constraint
    op.create_unique_constraint(
        "uq_currency_tenant_code",
        "currencies",
        ["tenant_id", "code"],
    )


def downgrade() -> None:
    op.drop_constraint("uq_currency_tenant_code", "currencies", type_="unique")
    op.execute("ALTER TABLE currencies ADD CONSTRAINT currencies_code_key UNIQUE (code)")
