-- 000044_personal_channels.sql — 个人渠道:门户用户自建 webhook 渠道,绑定已批准模型,
-- 入站消息用用户运行时凭据应答,用量归属用户自己的 Key。

CREATE TABLE IF NOT EXISTS gateway.personal_channels (
    id uuid PRIMARY KEY,
    portal_user_id uuid NOT NULL REFERENCES gateway.portal_users(id) ON DELETE CASCADE,
    code varchar(64) NOT NULL,
    name varchar(128) NOT NULL,
    kind varchar(16) NOT NULL DEFAULT 'webhook' CHECK (kind IN ('webhook')),
    inbound_token_hash varchar(64) NOT NULL,
    provider_code text NOT NULL DEFAULT '',
    model text NOT NULL CHECK (length(model) BETWEEN 1 AND 512),
    enabled boolean NOT NULL DEFAULT true,
    last_used_at timestamptz,
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    UNIQUE (code)
);

CREATE INDEX IF NOT EXISTS personal_channels_user_idx
    ON gateway.personal_channels (portal_user_id, created_at DESC);
