-- socialrsss MVP schema
-- 设计要点：
--   creators 是"跨平台合并单元"（一个人/一个 IP），同一 creator 可绑多个 accounts
--   accounts 是"单平台账号"，(platform, platform_uid) 唯一
--   items 是"抓回的内容"，read 标记直接放本表（单租户、不分用户）
--   去重靠 (account_id, platform_item_id) 唯一索引

CREATE TABLE IF NOT EXISTS creators (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    name        TEXT NOT NULL,
    note        TEXT DEFAULT '',
    created_at  TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS accounts (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    creator_id   INTEGER NOT NULL REFERENCES creators(id) ON DELETE CASCADE,
    platform     TEXT    NOT NULL CHECK (platform IN ('bilibili','xiaohongshu','douyin','kuaishou','weibo','zhihu','xiaoyuzhou','youtube','tiktok','cctv')),
    platform_uid TEXT    NOT NULL,
    display_name TEXT    DEFAULT '',
    last_fetched_at TEXT,
    enabled      INTEGER NOT NULL DEFAULT 1,
    created_at   TEXT    NOT NULL DEFAULT (datetime('now')),
    UNIQUE (platform, platform_uid)
);

CREATE INDEX IF NOT EXISTS idx_accounts_creator ON accounts(creator_id);

CREATE TABLE IF NOT EXISTS items (
    id                  INTEGER PRIMARY KEY AUTOINCREMENT,
    account_id          INTEGER NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    platform_item_id    TEXT    NOT NULL,
    title               TEXT    NOT NULL DEFAULT '',
    url                 TEXT    NOT NULL,
    cover_url           TEXT    DEFAULT '',
    duration_sec        INTEGER,
    published_at        TEXT    NOT NULL,
    fetched_at          TEXT    NOT NULL DEFAULT (datetime('now')),
    is_read             INTEGER NOT NULL DEFAULT 0,
    transcript_text     TEXT    DEFAULT '',
    transcript_segments TEXT    DEFAULT '',  -- JSON array
    transcript_source   TEXT    DEFAULT '',  -- 'subtitle' | 'asr_user_key' | 'asr_pack' | 'no_subtitle' | ''
    transcript_status   TEXT    NOT NULL DEFAULT 'pending',  -- pending | done | no_subtitle | failed | skipped
    cloud_pushed_at     TEXT,   -- ISO 时间；非空 = 已推送到 SaaS；NULL = 待推送
    UNIQUE (account_id, platform_item_id)
);

CREATE INDEX IF NOT EXISTS idx_items_published ON items(published_at DESC);
CREATE INDEX IF NOT EXISTS idx_items_unread    ON items(is_read, published_at DESC);
-- idx_items_transcript_status / idx_items_cloud_pending 在 db._apply_migrations 后创建，
-- 因为这些列在旧库里是 ALTER TABLE 加上的，先建索引会撞 "no such column"
