-- AI Conversations: persistent log of "Ask Ash" chat interactions
-- Stores per-message context (persona, pillar, intent) and the model's reply.
-- Used by the /api/ai/history endpoint to show recent chats to the user.

BEGIN;

CREATE TABLE IF NOT EXISTS ai_conversations (
    id            UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id       UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    persona       VARCHAR(32),                 -- companies | job_seekers | customers | professionals
    pillar        VARCHAR(32),                 -- create | complete | discover | improve
    query         TEXT NOT NULL,
    response      TEXT NOT NULL,
    intent        VARCHAR(64),                 -- detected intent (e.g. help_search, ticket_creation)
    confidence    REAL,                        -- intent confidence in [0, 1]
    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Hot path: "last 10 conversations for user X"
CREATE INDEX IF NOT EXISTS idx_ai_conversations_user_id_created_at
    ON ai_conversations (user_id, created_at DESC);

-- Optional grouping by conversation thread (frontend may pass a thread id).
CREATE INDEX IF NOT EXISTS idx_ai_conversations_user_pillar
    ON ai_conversations (user_id, pillar, created_at DESC);

COMMIT;
