-- TEC-2932: add a normalized-address column for duplicate detection
--
-- Strategy:
--   * Vietnamese-aware normalization done in application code (Address VO),
--     so the column is plain TEXT and is populated by the API layer.
--   * Backfill existing rows with an in-DB approximation
--     (LOWER + UNACCENT + collapse whitespace + trim). This keeps the
--     migration self-contained without requiring a TS backfill script.
--   * BTree index on (agentId-aware lookups via Listing) so equality
--     filtering is cheap. Address normalization is also valuable for
--     analytics/admin so we index the column itself.
--
-- The column is added nullable so the migration can be applied to a
-- production database without blocking writes; new inserts coming through
-- the API layer always populate the value.

CREATE EXTENSION IF NOT EXISTS "unaccent";

ALTER TABLE "Property"
  ADD COLUMN IF NOT EXISTS "addressNormalized" TEXT;

-- Backfill existing rows. The expression mirrors the application-level
-- Address.normalize() rule:
--   1. concatenate `address, ward, district, city`
--   2. unaccent (strip Vietnamese diacritics)
--   3. lowercase
--   4. replace any non-alphanumeric run with a single space
--   5. collapse whitespace and trim
UPDATE "Property"
SET "addressNormalized" = TRIM(
  REGEXP_REPLACE(
    LOWER(
      UNACCENT(
        CONCAT_WS(', ', "address", "ward", "district", "city")
      )
    ),
    '[^a-z0-9]+',
    ' ',
    'g'
  )
)
WHERE "addressNormalized" IS NULL;

-- Equality lookup index (used by duplicate detector + admin endpoint).
CREATE INDEX IF NOT EXISTS "Property_addressNormalized_idx"
  ON "Property" ("addressNormalized");
