-- Chat history Project Search (PostgreSQL geonet_project_search @ 10.100.1.25)
\connect geonet_project_search

CREATE TABLE IF NOT EXISTS project_search_chat_sessions (
    id              BIGSERIAL PRIMARY KEY,
    session_uuid    UUID NOT NULL UNIQUE,
    username        VARCHAR(255) NOT NULL,
    status          VARCHAR(32) NOT NULL DEFAULT 'active',
    sources         JSONB,
    started_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    ended_at        TIMESTAMPTZ,
    message_count   INTEGER NOT NULL DEFAULT 0
);

CREATE INDEX IF NOT EXISTS idx_ps_chat_sessions_user_status
    ON project_search_chat_sessions (username, status);

CREATE INDEX IF NOT EXISTS idx_ps_chat_sessions_started
    ON project_search_chat_sessions (started_at DESC);

CREATE TABLE IF NOT EXISTS project_search_chat_messages (
    id              BIGSERIAL PRIMARY KEY,
    session_id      BIGINT NOT NULL REFERENCES project_search_chat_sessions(id) ON DELETE CASCADE,
    role            VARCHAR(16) NOT NULL,
    content         TEXT NOT NULL,
    results         JSONB,
    meta            JSONB,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_ps_chat_messages_session
    ON project_search_chat_messages (session_id, id);

GRANT SELECT, INSERT, UPDATE, DELETE ON project_search_chat_sessions, project_search_chat_messages TO geonet_project;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO geonet_project;
