-- Enable pg_trgm for substring search via GIN indexes
CREATE EXTENSION IF NOT EXISTS pg_trgm;

-- Historical name aliases for persons (marriage, widowhood, etc.)
CREATE TABLE person_name_aliases (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    person_id   UUID NOT NULL REFERENCES persons(id) ON DELETE CASCADE,
    last_name   VARCHAR(255) NOT NULL,
    first_name  VARCHAR(255),
    type        VARCHAR(50) NOT NULL,
    sort_order  INTEGER NOT NULL DEFAULT 0,
    created_at  TIMESTAMPTZ DEFAULT now()
);

-- Indexes on alias table
CREATE INDEX idx_aliases_person_id ON person_name_aliases(person_id);
CREATE INDEX idx_aliases_last_name_trgm ON person_name_aliases USING GIN (lower(last_name) gin_trgm_ops);

-- Retroactive GIN trigram indexes on existing persons table for substring search
CREATE INDEX idx_persons_first_name_trgm ON persons USING GIN (lower(first_name) gin_trgm_ops);
CREATE INDEX idx_persons_last_name_trgm ON persons USING GIN (lower(last_name) gin_trgm_ops);
CREATE INDEX idx_persons_alias_trgm ON persons USING GIN (lower(alias) gin_trgm_ops);
