"""Email Templates — unique index on (tenant_id, name) for active rows

Revision ID: 0055
Revises: 0054
Create Date: 2026-07-02

Backs the existing SELECT-then-INSERT duplicate-name check in
EmailTemplateService.create()/update() with a real DB constraint, closing a
race window where two concurrent requests could both pass the pre-check
before either commits (INDL-32 code review — race condition finding).

The service still performs the SELECT pre-check first (friendlier/faster
failure in the common case); this index is the safety net, surfaced to the
service as an IntegrityError that is translated back into the same
ConflictError / 409 response.
"""
from alembic import op
import sqlalchemy as sa

revision = "0055"
down_revision = "0054"
branch_labels = None
depends_on = None


def upgrade() -> None:
    conn = op.get_bind()
    conn.execute(sa.text(
        """
        CREATE UNIQUE INDEX IF NOT EXISTS uq_email_templates_tenant_name
        ON email_templates (tenant_id, name)
        WHERE deleted_at IS NULL
        """
    ))


def downgrade() -> None:
    conn = op.get_bind()
    conn.execute(sa.text(
        "DROP INDEX IF EXISTS uq_email_templates_tenant_name"
    ))
