-- rBooks schema — community PDF library
-- Runs inside the `rbooks` schema (set by migration runner)

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE IF NOT EXISTS books (
  id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  slug            TEXT NOT NULL UNIQUE,
  title           TEXT NOT NULL,
  author          TEXT,
  description     TEXT,
  pdf_path        TEXT NOT NULL,
  pdf_size_bytes  BIGINT DEFAULT 0,
  page_count      INTEGER DEFAULT 0,
  tags            TEXT[] DEFAULT '{}',
  license         TEXT DEFAULT 'CC BY-SA 4.0',
  cover_color     TEXT DEFAULT '#334155',
  contributor_id  TEXT,
  contributor_name TEXT,
  status          TEXT NOT NULL DEFAULT 'published',
  featured        BOOLEAN DEFAULT FALSE,
  view_count      INTEGER DEFAULT 0,
  download_count  INTEGER DEFAULT 0,
  created_at      TIMESTAMPTZ DEFAULT NOW(),
  updated_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_books_status ON books (status) WHERE status = 'published';
CREATE INDEX IF NOT EXISTS idx_books_slug ON books (slug);
CREATE INDEX IF NOT EXISTS idx_books_featured ON books (featured) WHERE featured = TRUE;
CREATE INDEX IF NOT EXISTS idx_books_created ON books (created_at DESC);
