-- 008: Persistent inter-agent messaging (email-style inbox)

CREATE TABLE IF NOT EXISTS messages (
    id          TEXT PRIMARY KEY,
    project_id  UUID NOT NULL REFERENCES projects(id),
    from_agent  TEXT NOT NULL DEFAULT 'unknown',
    to_agent    TEXT NOT NULL,
    thread_id   TEXT NOT NULL,
    body        TEXT NOT NULL,
    archived_at TIMESTAMPTZ,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Inbox queries: fetch messages for a specific agent (direct + broadcast)
CREATE INDEX IF NOT EXISTS idx_messages_project_to
    ON messages (project_id, to_agent, created_at DESC);

-- Sent queries: fetch messages from a specific agent
CREATE INDEX IF NOT EXISTS idx_messages_project_from
    ON messages (project_id, from_agent, created_at DESC);

-- Thread grouping
CREATE INDEX IF NOT EXISTS idx_messages_thread
    ON messages (thread_id, created_at ASC);

-- Broadcast filter (for unread count queries)
CREATE INDEX IF NOT EXISTS idx_messages_broadcast
    ON messages (project_id, created_at DESC) WHERE to_agent = 'broadcast';

-- Per-agent read tracking (needed for broadcasts)
CREATE TABLE IF NOT EXISTS message_reads (
    message_id  TEXT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
    agent_id    TEXT NOT NULL,
    read_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (message_id, agent_id)
);
