"""Enable pg_trgm for typo-tolerant public record search (INDL-46 follow-up)

The public "Find a loved one" search (GET /api/public/records) uses
``similarity()`` so common misspellings still find a record. That function is
provided by the pg_trgm extension. Also adds GIN trigram indexes on the searched
name columns so the fuzzy match stays fast as records grow.

NOTE (2026-07-03, INDL-52): this file originally claimed revision id "0058"
with down_revision "0057", independently of
0058_account_status_canceled_spelling.py which also claimed "0058" off
"0057" — both were merged into `develop` without noticing the collision,
and only the account_status branch was ever actually applied to existing
databases (pg_trgm extension confirmed absent on the dev DB before this
fix). Renumbered to "0058b", chained after 0058a
(memorial_public_page_fields), following this repo's existing convention
for resolving revision-id collisions (see 0004a, 0007b, 0038a). No DDL
below was changed.
"""
from alembic import op
import sqlalchemy as sa

revision = "0058b"
down_revision = "0058a"
branch_labels = None
depends_on = None


def upgrade() -> None:
    conn = op.get_bind()
    conn.execute(sa.text("CREATE EXTENSION IF NOT EXISTS pg_trgm"))
    conn.execute(sa.text(
        "CREATE INDEX IF NOT EXISTS ix_records_first_name_trgm "
        "ON records USING gin (lower(first_name) gin_trgm_ops)"
    ))
    conn.execute(sa.text(
        "CREATE INDEX IF NOT EXISTS ix_records_last_name_trgm "
        "ON records USING gin (lower(last_name) gin_trgm_ops)"
    ))


def downgrade() -> None:
    conn = op.get_bind()
    conn.execute(sa.text("DROP INDEX IF EXISTS ix_records_last_name_trgm"))
    conn.execute(sa.text("DROP INDEX IF EXISTS ix_records_first_name_trgm"))
    # Leave the pg_trgm extension in place — other features may rely on it.
