-- ============================================================
-- V1: Initial schema
-- Spring AI manages the vector_store table separately.
-- ============================================================

CREATE TABLE IF NOT EXISTS book (
    id               UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    title            VARCHAR(500) NOT NULL,
    file_name        VARCHAR(500) NOT NULL,
    file_size_bytes  BIGINT NOT NULL,
    page_count       INT,
    status           VARCHAR(20) NOT NULL DEFAULT 'PENDING',
    error_message    TEXT,
    uploaded_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    processed_at     TIMESTAMPTZ
);

CREATE TABLE IF NOT EXISTS chat_session (
    id         UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    topic_id   VARCHAR(100),
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS message (
    id         UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id UUID NOT NULL REFERENCES chat_session(id) ON DELETE CASCADE,
    role       VARCHAR(10) NOT NULL,
    content    TEXT NOT NULL,
    sources    JSONB,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_message_session ON message(session_id, created_at);
