CREATE TABLE IF NOT EXISTS outline_items (
    id                  TEXT PRIMARY KEY,
    parent_id           TEXT,
    title               TEXT NOT NULL,
    description         TEXT DEFAULT '',
    status              TEXT NOT NULL DEFAULT 'pending',
    expected_word_count INTEGER DEFAULT NULL,
    chapter_id          TEXT,
    sort_order          INTEGER NOT NULL DEFAULT 0,
    created_at          TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at          TEXT NOT NULL DEFAULT (datetime('now')),
    FOREIGN KEY (parent_id) REFERENCES outline_items(id) ON DELETE CASCADE,
    FOREIGN KEY (chapter_id) REFERENCES chapters(id) ON DELETE SET NULL
);

CREATE TABLE IF NOT EXISTS settings (
    id          TEXT PRIMARY KEY,
    type        TEXT NOT NULL,
    name        TEXT NOT NULL,
    description TEXT DEFAULT '',
    properties  TEXT DEFAULT '{}',
    created_at  TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at  TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS setting_chapter_refs (
    setting_id  TEXT NOT NULL,
    chapter_id  TEXT NOT NULL,
    PRIMARY KEY (setting_id, chapter_id),
    FOREIGN KEY (setting_id) REFERENCES settings(id) ON DELETE CASCADE,
    FOREIGN KEY (chapter_id) REFERENCES chapters(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS inspiration (
    id          TEXT PRIMARY KEY,
    title       TEXT NOT NULL DEFAULT '',
    content     TEXT NOT NULL DEFAULT '',
    tags        TEXT DEFAULT '[]',
    created_at  TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at  TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS snapshots (
    id          TEXT PRIMARY KEY,
    chapter_id  TEXT NOT NULL,
    type        TEXT NOT NULL,
    name        TEXT DEFAULT '',
    content     TEXT NOT NULL,
    created_at  TEXT NOT NULL DEFAULT (datetime('now')),
    FOREIGN KEY (chapter_id) REFERENCES chapters(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS bookmarks (
    id            TEXT PRIMARY KEY,
    chapter_id    TEXT NOT NULL,
    position      INTEGER NOT NULL,
    label         TEXT NOT NULL,
    landmark_type TEXT NOT NULL DEFAULT 'todo',
    resolved      INTEGER NOT NULL DEFAULT 0,
    created_at    TEXT NOT NULL DEFAULT (datetime('now')),
    FOREIGN KEY (chapter_id) REFERENCES chapters(id) ON DELETE CASCADE
);

CREATE VIRTUAL TABLE IF NOT EXISTS search_fts USING fts5(
    source_kind,
    source_id,
    title,
    body,
    tokenize='unicode61'
);
