-- Geschichten: blog-like family memory stories linked to persons and documents (issue #381).
-- BLOG_WRITE permission gates authoring; DRAFT stories are never returned to readers.

CREATE TABLE geschichten (
    id              UUID PRIMARY KEY,
    title           VARCHAR(255) NOT NULL,
    body            TEXT,
    status          VARCHAR(32)  NOT NULL,
    author_id       UUID         REFERENCES users (id) ON DELETE SET NULL,
    created_at      TIMESTAMP    NOT NULL,
    updated_at      TIMESTAMP    NOT NULL,
    published_at    TIMESTAMP
);

CREATE TABLE geschichten_persons (
    geschichte_id   UUID NOT NULL REFERENCES geschichten (id) ON DELETE CASCADE,
    person_id       UUID NOT NULL REFERENCES persons      (id) ON DELETE CASCADE,
    PRIMARY KEY (geschichte_id, person_id)
);

CREATE TABLE geschichten_documents (
    geschichte_id   UUID NOT NULL REFERENCES geschichten (id) ON DELETE CASCADE,
    document_id     UUID NOT NULL REFERENCES documents   (id) ON DELETE CASCADE,
    PRIMARY KEY (geschichte_id, document_id)
);

-- Index page query: WHERE status = 'PUBLISHED' ORDER BY published_at DESC.
CREATE INDEX idx_geschichten_published
    ON geschichten (published_at DESC)
    WHERE status = 'PUBLISHED';

-- Reverse-lookup indexes for the ?personId / ?documentId filters.
CREATE INDEX idx_geschichten_persons_person     ON geschichten_persons   (person_id);
CREATE INDEX idx_geschichten_documents_document ON geschichten_documents (document_id);
