-- Add chat grouping + context source to Argus chat history

ALTER TABLE "argus_chat_history"
  ADD COLUMN IF NOT EXISTS "context_source" text,
  ADD COLUMN IF NOT EXISTS "chat_group_id" text,
  ADD COLUMN IF NOT EXISTS "chat_group_status" text,
  ADD COLUMN IF NOT EXISTS "chat_group_title" text;

-- Query patterns:
-- 1) history load: user+project+domain+context_source (+ trace/session/app) + chat_group_id ordered by created_at desc
-- 2) chat list: same scope, group by chat_group_id
CREATE INDEX IF NOT EXISTS "argus_chat_history_context_group_idx"
ON "argus_chat_history"
USING btree ("project_id", "user_id", "type", "context_source", "chat_group_id", "created_at" DESC);

CREATE INDEX IF NOT EXISTS "argus_chat_history_context_lookup_idx"
ON "argus_chat_history"
USING btree ("project_id", "user_id", "type", "context_source", "trace_id", "session_id", "application_id", "test_run_id", "created_at" DESC);

