-- Add tsvector column to MantisIssue for title and description
ALTER TABLE "MantisIssue" ADD COLUMN "fts" tsvector;

-- Create function to update MantisIssue fts column
CREATE OR REPLACE FUNCTION update_mantisissue_fts() RETURNS trigger AS $$
BEGIN
  NEW.fts := to_tsvector('english', coalesce(NEW.title, '') || ' ' || coalesce(NEW.description, ''));
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Create trigger to update MantisIssue fts column on insert or update
CREATE TRIGGER mantisissue_fts_update
BEFORE INSERT OR UPDATE ON "MantisIssue"
FOR EACH ROW EXECUTE FUNCTION update_mantisissue_fts();

-- Update existing rows in MantisIssue
UPDATE "MantisIssue" SET fts = to_tsvector('english', coalesce(title, '') || ' ' || coalesce(description, ''));

-- Create index on MantisIssue fts column
CREATE INDEX mantisissue_fts_idx ON "MantisIssue" USING gin(fts);


-- Add tsvector column to MantisComment for comment text
ALTER TABLE "MantisComment" ADD COLUMN "fts" tsvector;

-- Create function to update MantisComment fts column
CREATE OR REPLACE FUNCTION update_mantiscomment_fts() RETURNS trigger AS $$
BEGIN
  NEW.fts := to_tsvector('english', coalesce(NEW.comment, ''));
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Create trigger to update MantisComment fts column on insert or update
CREATE TRIGGER mantiscomment_fts_update
BEFORE INSERT OR UPDATE ON "MantisComment"
FOR EACH ROW EXECUTE FUNCTION update_mantiscomment_fts();

-- Update existing rows in MantisComment
UPDATE "MantisComment" SET fts = to_tsvector('english', coalesce(comment, ''));

-- Create index on MantisComment fts column
CREATE INDEX mantiscomment_fts_idx ON "MantisComment" USING gin(fts);