-- 旗舰版资源市场：MCP 服务器 / Skills / 数字员工
-- 三类可发布资产 + 共享分类 + 市场安装（工作区绑定 + 权限）。

-- 共享市场分类（resource_type = '' 表示全局分类，适用所有资源类型）
CREATE TABLE IF NOT EXISTS gateway.marketplace_categories (
    id uuid PRIMARY KEY,
    name text NOT NULL UNIQUE,
    description text NOT NULL DEFAULT '',
    resource_type text NOT NULL DEFAULT ''
        CHECK (resource_type IN ('', 'mcp_server', 'skill', 'digital_employee')),
    sort_order integer NOT NULL DEFAULT 0 CHECK (sort_order >= 0),
    created_by uuid REFERENCES gateway.admin_accounts(id),
    created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);

-- MCP 服务器：连接外部 MCP 服务器的注册信息（transport/endpoint/凭证）
CREATE TABLE IF NOT EXISTS gateway.mcp_servers (
    id uuid PRIMARY KEY,
    code text NOT NULL UNIQUE CHECK (code ~ '^[a-z][a-z0-9_-]{1,63}$'),
    name text NOT NULL,
    description text NOT NULL DEFAULT '',
    transport text NOT NULL DEFAULT 'streamable-http'
        CHECK (transport IN ('streamable-http', 'sse')),
    endpoint_url text NOT NULL,
    encrypted_headers bytea NOT NULL DEFAULT ''::bytea,
    headers_kek_version integer NOT NULL DEFAULT 1,
    status text NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),
    category_id uuid REFERENCES gateway.marketplace_categories(id) ON DELETE SET NULL,
    tags text[] NOT NULL DEFAULT '{}',
    department_ids uuid[] NOT NULL DEFAULT '{}',
    enabled boolean NOT NULL DEFAULT true,
    revision bigint NOT NULL DEFAULT 1,
    created_by uuid REFERENCES gateway.admin_accounts(id),
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);

-- Skills：带绑定的提示词包（content + variables + 工具/MCP/知识库绑定）
CREATE TABLE IF NOT EXISTS gateway.skills (
    id uuid PRIMARY KEY,
    code text NOT NULL UNIQUE CHECK (code ~ '^[a-z][a-z0-9_-]{1,63}$'),
    name text NOT NULL,
    description text NOT NULL DEFAULT '',
    content text NOT NULL CHECK (length(content) BETWEEN 1 AND 100000),
    variables jsonb NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(variables) = 'array'),
    tool_ids uuid[] NOT NULL DEFAULT '{}',
    mcp_server_ids uuid[] NOT NULL DEFAULT '{}',
    knowledge_base_ids uuid[] NOT NULL DEFAULT '{}',
    status text NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),
    category_id uuid REFERENCES gateway.marketplace_categories(id) ON DELETE SET NULL,
    tags text[] NOT NULL DEFAULT '{}',
    department_ids uuid[] NOT NULL DEFAULT '{}',
    enabled boolean NOT NULL DEFAULT true,
    revision bigint NOT NULL DEFAULT 1,
    created_by uuid REFERENCES gateway.admin_accounts(id),
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);

-- 数字员工：复合编排（persona + 模型 + 技能/工具/MCP/知识库绑定 + 生成参数）
CREATE TABLE IF NOT EXISTS gateway.digital_employees (
    id uuid PRIMARY KEY,
    code text NOT NULL UNIQUE CHECK (code ~ '^[a-z][a-z0-9_-]{2,63}$'),
    name text NOT NULL,
    description text NOT NULL DEFAULT '',
    persona text NOT NULL DEFAULT '',
    model text NOT NULL DEFAULT '',
    skill_ids uuid[] NOT NULL DEFAULT '{}',
    tool_ids uuid[] NOT NULL DEFAULT '{}',
    mcp_server_ids uuid[] NOT NULL DEFAULT '{}',
    knowledge_base_ids uuid[] NOT NULL DEFAULT '{}',
    temperature numeric NOT NULL DEFAULT 0.7 CHECK (temperature >= 0 AND temperature <= 2),
    retrieval_top_k integer NOT NULL DEFAULT 5 CHECK (retrieval_top_k BETWEEN 1 AND 50),
    max_tool_rounds integer NOT NULL DEFAULT 5 CHECK (max_tool_rounds BETWEEN 1 AND 20),
    status text NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),
    category_id uuid REFERENCES gateway.marketplace_categories(id) ON DELETE SET NULL,
    tags text[] NOT NULL DEFAULT '{}',
    department_ids uuid[] NOT NULL DEFAULT '{}',
    enabled boolean NOT NULL DEFAULT true,
    revision bigint NOT NULL DEFAULT 1,
    created_by uuid REFERENCES gateway.admin_accounts(id),
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);

CREATE TABLE IF NOT EXISTS gateway.digital_employee_runs (
    id uuid PRIMARY KEY,
    digital_employee_id uuid NOT NULL REFERENCES gateway.digital_employees(id) ON DELETE CASCADE,
    api_key_id uuid REFERENCES gateway.api_keys(id) ON DELETE SET NULL,
    request_id text NOT NULL,
    status text NOT NULL CHECK (status IN ('success', 'error')),
    latency_ms bigint NOT NULL DEFAULT 0,
    retrieval_count integer NOT NULL DEFAULT 0,
    tool_count integer NOT NULL DEFAULT 0,
    error text NOT NULL DEFAULT '',
    created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);

CREATE INDEX IF NOT EXISTS digital_employee_runs_de_time_idx
    ON gateway.digital_employee_runs (digital_employee_id, created_at DESC);

-- 市场安装：portal 用户工作区绑定（资源权限：跨部门使用需先安装）
CREATE TABLE IF NOT EXISTS gateway.marketplace_installations (
    id uuid PRIMARY KEY,
    resource_type text NOT NULL
        CHECK (resource_type IN ('mcp_server', 'skill', 'digital_employee')),
    resource_id uuid NOT NULL,
    portal_user_id uuid NOT NULL REFERENCES gateway.portal_users(id) ON DELETE CASCADE,
    config_override jsonb NOT NULL DEFAULT '{}'::jsonb CHECK (jsonb_typeof(config_override) = 'object'),
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    UNIQUE (resource_type, resource_id, portal_user_id)
);

CREATE INDEX IF NOT EXISTS marketplace_installations_user_idx
    ON gateway.marketplace_installations (portal_user_id);

-- 市场可见性：published + enabled 的资源按更新时间倒序
CREATE INDEX IF NOT EXISTS mcp_servers_visible_idx
    ON gateway.mcp_servers (status, enabled, updated_at DESC);
CREATE INDEX IF NOT EXISTS skills_visible_idx
    ON gateway.skills (status, enabled, updated_at DESC);
CREATE INDEX IF NOT EXISTS digital_employees_visible_idx
    ON gateway.digital_employees (status, enabled, updated_at DESC);

COMMENT ON TABLE gateway.mcp_servers IS
    'Marketplace MCP server registrations (streamable-http/sse). Tools are discovered live via the MCP client, not stored.';
COMMENT ON TABLE gateway.digital_employees IS
    'Composite digital employees: persona + model + bound skills/tools/MCP servers/knowledge bases.';
COMMENT ON TABLE gateway.marketplace_installations IS
    'Portal workspace bindings granting cross-department access to published marketplace resources.';
