-- M-P01: pg_trgm GIN indexes on the leading-wildcard ILIKE search
-- columns used by `buildListQuery` (src/lib/db/query-builder.ts:67).
--
-- Without these, every `ILIKE '%term%'` predicate sequential-scans
-- the entire table. The fix isn't to rewrite the SQL - Postgres will
-- transparently use a `gin_trgm_ops` index for ILIKE patterns once
-- one exists on the column.
--
-- The pg_trgm extension is a one-time install; CREATE EXTENSION IF NOT
-- EXISTS is idempotent. Each CREATE INDEX CONCURRENTLY runs outside
-- a transaction (the db-migrate runner detects CONCURRENTLY and
-- splits the statement out of the wrapping tx).

CREATE EXTENSION IF NOT EXISTS pg_trgm;
--> statement-breakpoint

-- ─── Clients ──────────────────────────────────────────────────────────────
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_clients_full_name_trgm
  ON clients USING gin (full_name gin_trgm_ops);
--> statement-breakpoint

-- ─── Yachts ──────────────────────────────────────────────────────────────
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_yachts_name_trgm
  ON yachts USING gin (name gin_trgm_ops);
--> statement-breakpoint

CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_yachts_builder_trgm
  ON yachts USING gin (builder gin_trgm_ops);
--> statement-breakpoint

-- ─── Companies ───────────────────────────────────────────────────────────
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_companies_name_trgm
  ON companies USING gin (name gin_trgm_ops);
--> statement-breakpoint

-- ─── Berths ──────────────────────────────────────────────────────────────
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_berths_mooring_number_trgm
  ON berths USING gin (mooring_number gin_trgm_ops);
--> statement-breakpoint

-- ─── Residential clients (parallel client surface) ───────────────────────
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_residential_clients_full_name_trgm
  ON residential_clients USING gin (full_name gin_trgm_ops);
--> statement-breakpoint

-- ─── Tags (filter-bar autocomplete) ──────────────────────────────────────
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tags_name_trgm
  ON tags USING gin (name gin_trgm_ops);
