-- 008: Wiki System

CREATE TABLE IF NOT EXISTS wiki_page (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    repo_id UUID NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
    slug TEXT NOT NULL,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    author_id UUID NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
    last_editor_id UUID REFERENCES "user"(id) ON DELETE SET NULL,
    version INTEGER NOT NULL DEFAULT 1,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMPTZ NULL,
    CONSTRAINT uq_wiki_page_repo_slug UNIQUE (repo_id, slug)
);

CREATE TABLE IF NOT EXISTS wiki_page_revision (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    page_id UUID NOT NULL REFERENCES wiki_page(id) ON DELETE CASCADE,
    version INTEGER NOT NULL,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    editor_id UUID NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
    commit_message TEXT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT uq_wiki_revision_page_version UNIQUE (page_id, version)
);

CREATE INDEX IF NOT EXISTS idx_wiki_page_repo_id ON wiki_page(repo_id);
CREATE INDEX IF NOT EXISTS idx_wiki_page_slug ON wiki_page(slug);
CREATE INDEX IF NOT EXISTS idx_wiki_page_deleted_at ON wiki_page(deleted_at) WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_wiki_revision_page_id ON wiki_page_revision(page_id);
CREATE INDEX IF NOT EXISTS idx_wiki_revision_version ON wiki_page_revision(version);
