-- LLM chat message history
-- Each row stores one message (user or assistant) for a given user.
CREATE TABLE IF NOT EXISTS public.llm_messages (
  id          UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id     UUID        NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
  role        TEXT        NOT NULL CHECK (role IN ('user', 'assistant')),
  content     TEXT        NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Row Level Security: users can only access their own messages.
ALTER TABLE public.llm_messages ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can manage their own llm messages"
  ON public.llm_messages
  FOR ALL
  USING  (auth.uid() = user_id)
  WITH CHECK (auth.uid() = user_id);

-- Index for fast ordered queries per user.
CREATE INDEX IF NOT EXISTS llm_messages_user_created_at_idx
  ON public.llm_messages (user_id, created_at ASC);
