-- Enterprise-side feature permission configuration.
-- These records back the operation console "权限配置" page and mirror the
-- client enterprise configuration capabilities: team, usage and model setup.

CREATE TABLE IF NOT EXISTS permission_policies
(
    code          VARCHAR(64)  NOT NULL,
    name          VARCHAR(80)  NOT NULL,
    category      VARCHAR(40)  NOT NULL,
    scope         VARCHAR(80)  NOT NULL,
    description   VARCHAR(255) NOT NULL,
    default_roles VARCHAR(120) DEFAULT NULL,
    status        TINYINT      NOT NULL DEFAULT 1,
    sort_order    INT          NOT NULL DEFAULT 0,
    created_at    DATETIME(3)  NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    updated_at    DATETIME(3)  NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    PRIMARY KEY (code),
    KEY idx_permission_category (category, status, sort_order)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT '企业成员功能权限项';

CREATE TABLE IF NOT EXISTS tenant_member_permissions
(
    id               BIGINT       NOT NULL AUTO_INCREMENT,
    tenant_id        BIGINT       NOT NULL,
    user_id          BIGINT       NOT NULL,
    policy_code      VARCHAR(64)  NOT NULL,
    permission_level VARCHAR(24)  NOT NULL DEFAULT '允许',
    data_scope       VARCHAR(80)  NOT NULL DEFAULT '本企业',
    grant_source     VARCHAR(80)  NOT NULL DEFAULT '运营配置',
    status           TINYINT      NOT NULL DEFAULT 1,
    granted_by       BIGINT                DEFAULT NULL,
    granted_at       DATETIME(3)  NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    revoked_at       DATETIME(3)           DEFAULT NULL,
    remark           VARCHAR(255)          DEFAULT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uk_tenant_user_policy (tenant_id, user_id, policy_code),
    KEY idx_tenant_policy (tenant_id, policy_code, status),
    KEY idx_user_policy (user_id, policy_code, status)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT '企业成员权限配置';

INSERT INTO permission_policies (code, name, category, scope, description, default_roles, status, sort_order)
VALUES
    ('TEAM_MANAGE', '团队管理', '企业配置', '企业成员与组织关系', '邀请、编辑、禁用成员并维护组织角色。', 'owner,admin', 1, 10),
    ('USAGE_VIEW', '用量统计', '企业配置', '资源流水与模型消耗', '查看企业用量、积分流水、模型消耗和导出统计。', 'owner,admin,member', 1, 20),
    ('MODEL_CONFIG', '模型配置', '企业配置', '模型供应商与默认模型', '维护企业接入的模型供应商、模型清单和默认模型。', 'owner,admin', 1, 30),
    ('PROJECT_MANAGE', '项目管理', '创作工具', '短剧项目与任务', '创建、编辑、删除项目并管理生成任务。', 'owner,admin,member', 1, 40),
    ('ASSET_MANAGE', '资产管理', '创作工具', '角色、场景、素材资产', '上传、复用和管理企业资产库。', 'owner,admin,member', 1, 50),
    ('BILLING_MANAGE', '费用管理', '费用', '套餐、订单与发票', '管理套餐、充值、发票与退款处理。', 'owner,admin', 1, 60),
    ('SECURITY_AUDIT', '安全审计', '备案', '操作记录与合规确认', '查看企业侧关键操作记录和政策确认状态。', 'owner', 1, 70)
ON DUPLICATE KEY UPDATE
    name = VALUES(name),
    category = VALUES(category),
    scope = VALUES(scope),
    description = VALUES(description),
    default_roles = VALUES(default_roles),
    status = VALUES(status),
    sort_order = VALUES(sort_order);

INSERT INTO tenant_member_permissions
    (tenant_id, user_id, policy_code, permission_level, data_scope, grant_source, status, granted_by, granted_at, remark)
SELECT tm.tenant_id,
       tm.user_id,
       pp.code,
       '允许',
       CASE
           WHEN tm.role = 'owner' THEN '企业全部数据'
           WHEN tm.role = 'admin' THEN '企业运营数据'
           ELSE '本人参与项目'
       END,
       '按组织角色初始化',
       1,
       1,
       CURRENT_TIMESTAMP(3),
       CONCAT('由成员角色 ', tm.role, ' 自动初始化')
  FROM tenant_members tm
  JOIN users u ON u.id = tm.user_id AND u.deleted_at IS NULL
  JOIN tenants t ON t.id = tm.tenant_id AND t.deleted_at IS NULL
  JOIN permission_policies pp ON (
        tm.role = 'owner'
        OR (tm.role = 'admin' AND pp.code IN ('TEAM_MANAGE', 'USAGE_VIEW', 'MODEL_CONFIG', 'PROJECT_MANAGE', 'ASSET_MANAGE', 'BILLING_MANAGE'))
        OR (tm.role NOT IN ('owner', 'admin') AND pp.code IN ('USAGE_VIEW', 'PROJECT_MANAGE', 'ASSET_MANAGE'))
  )
  LEFT JOIN tenant_member_permissions existing
    ON existing.tenant_id = tm.tenant_id
   AND existing.user_id = tm.user_id
   AND existing.policy_code = pp.code
 WHERE existing.id IS NULL;
