-- Migration 023: Document Full-Text Search
-- Adds tsvector column and GIN index for fast document searching

-- Add search vector column
ALTER TABLE public.documents
ADD COLUMN IF NOT EXISTS search_vector tsvector;

-- Populate existing documents
UPDATE public.documents
SET search_vector = to_tsvector('english',
  coalesce(title, '') || ' ' ||
  coalesce(description, '') || ' ' ||
  coalesce(file_name, '')
);

-- Create GIN index for fast full-text search
CREATE INDEX IF NOT EXISTS idx_documents_search
ON public.documents USING GIN (search_vector);

-- Create trigger to keep search_vector updated
CREATE OR REPLACE FUNCTION update_document_search_vector()
RETURNS TRIGGER AS $$
BEGIN
  NEW.search_vector := to_tsvector('english',
    coalesce(NEW.title, '') || ' ' ||
    coalesce(NEW.description, '') || ' ' ||
    coalesce(NEW.file_name, '')
  );
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_update_document_search ON public.documents;
CREATE TRIGGER trg_update_document_search
  BEFORE INSERT OR UPDATE OF title, description, file_name
  ON public.documents
  FOR EACH ROW
  EXECUTE FUNCTION update_document_search_vector();
