CREATE TABLE IF NOT EXISTS channel_article (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    channel UUID NOT NULL REFERENCES room(id) ON DELETE CASCADE,
    author UUID NOT NULL,
    title TEXT NOT NULL,
    cover_url TEXT,
    content TEXT NOT NULL DEFAULT '',
    content_type TEXT NOT NULL DEFAULT 'markdown',
    summary TEXT,
    tags TEXT[] NOT NULL DEFAULT '{}',
    is_pinned BOOLEAN NOT NULL DEFAULT FALSE,
    view_count BIGINT NOT NULL DEFAULT 0,
    like_count BIGINT NOT NULL DEFAULT 0,
    comment_count BIGINT NOT NULL DEFAULT 0,
    status TEXT NOT NULL DEFAULT 'published',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    deleted_at TIMESTAMPTZ
);

-- Index for waterfall feed queries: by channel, pinned first, then by created_at desc
CREATE INDEX IF NOT EXISTS idx_channel_article_feed
    ON channel_article (channel, is_pinned DESC, created_at DESC)
    WHERE deleted_at IS NULL;

-- Index for author lookup
CREATE INDEX IF NOT EXISTS idx_channel_article_author
    ON channel_article (author, created_at DESC);
