USE datamate;

-- =============================================
-- 认证与授权（RBAC）基础表
-- 注意：该脚本命名为 zz- 前缀，确保在 users 表初始化后执行
-- =============================================

CREATE TABLE IF NOT EXISTS t_auth_roles
(
    id          VARCHAR(36) PRIMARY KEY COMMENT '角色ID',
    role_code   VARCHAR(100) NOT NULL COMMENT '角色编码',
    role_name   VARCHAR(100) NOT NULL COMMENT '角色名称',
    description VARCHAR(255) DEFAULT '' COMMENT '角色描述',
    enabled     TINYINT      DEFAULT 1 COMMENT '是否启用：1-启用，0-禁用',
    is_built_in TINYINT      DEFAULT 1 COMMENT '是否内置：1-是，0-否',
    created_at  TIMESTAMP    DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at  TIMESTAMP    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    UNIQUE KEY uk_auth_role_code (role_code)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4 COMMENT ='角色表';

CREATE TABLE IF NOT EXISTS t_auth_permissions
(
    id              VARCHAR(36) PRIMARY KEY COMMENT '权限ID',
    permission_code VARCHAR(120) NOT NULL COMMENT '权限编码',
    permission_name VARCHAR(120) NOT NULL COMMENT '权限名称',
    module          VARCHAR(100) NOT NULL COMMENT '模块',
    action          VARCHAR(50)  NOT NULL COMMENT '动作',
    path_pattern    VARCHAR(255) DEFAULT '' COMMENT '路径模式',
    method          VARCHAR(20)  DEFAULT '' COMMENT 'HTTP方法',
    enabled         TINYINT      DEFAULT 1 COMMENT '是否启用：1-启用，0-禁用',
    is_built_in     TINYINT      DEFAULT 1 COMMENT '是否内置：1-是，0-否',
    created_at      TIMESTAMP    DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at      TIMESTAMP    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    UNIQUE KEY uk_auth_permission_code (permission_code),
    INDEX idx_auth_permission_module_action (module, action)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4 COMMENT ='权限表';

CREATE TABLE IF NOT EXISTS t_auth_role_permissions
(
    id            BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键',
    role_id       VARCHAR(36) NOT NULL COMMENT '角色ID',
    permission_id VARCHAR(36) NOT NULL COMMENT '权限ID',
    created_at    TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    UNIQUE KEY uk_auth_role_permission (role_id, permission_id),
    INDEX idx_auth_role_permission_role (role_id),
    INDEX idx_auth_role_permission_permission (permission_id),
    CONSTRAINT fk_auth_rp_role FOREIGN KEY (role_id) REFERENCES t_auth_roles (id) ON DELETE CASCADE,
    CONSTRAINT fk_auth_rp_permission FOREIGN KEY (permission_id) REFERENCES t_auth_permissions (id) ON DELETE CASCADE
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4 COMMENT ='角色权限关系表';

CREATE TABLE IF NOT EXISTS t_auth_user_roles
(
    id         BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键',
    user_id    BIGINT      NOT NULL COMMENT '用户ID（users.id）',
    role_id    VARCHAR(36) NOT NULL COMMENT '角色ID',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    UNIQUE KEY uk_auth_user_role (user_id, role_id),
    INDEX idx_auth_user_role_user (user_id),
    INDEX idx_auth_user_role_role (role_id),
    CONSTRAINT fk_auth_ur_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
    CONSTRAINT fk_auth_ur_role FOREIGN KEY (role_id) REFERENCES t_auth_roles (id) ON DELETE CASCADE
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4 COMMENT ='用户角色关系表';

-- =============================================
-- 角色初始化
-- =============================================
INSERT IGNORE INTO t_auth_roles (id, role_code, role_name, description, enabled, is_built_in)
VALUES ('role-admin', 'ROLE_ADMIN', '系统管理员', '拥有平台全部权限', 1, 1),
       ('role-data-editor', 'ROLE_DATA_EDITOR', '数据运营', '拥有业务模块读写权限', 1, 1),
       ('role-knowledge-user', 'ROLE_KNOWLEDGE_USER', '知识用户', '以知识管理为主的业务权限', 1, 1);

-- =============================================
-- 权限初始化（接口级）
-- =============================================
INSERT IGNORE INTO t_auth_permissions (id, permission_code, permission_name, module, action, path_pattern, method, enabled, is_built_in)
VALUES ('perm-dm-read', 'module:data-management:read', '数据管理读取', 'data-management', 'read', '/api/data-management/**', 'GET', 1, 1),
       ('perm-dm-write', 'module:data-management:write', '数据管理写入', 'data-management', 'write', '/api/data-management/**', 'POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-da-read', 'module:data-annotation:read', '数据标注读取', 'data-annotation', 'read', '/api/annotation/**', 'GET', 1, 1),
       ('perm-da-write', 'module:data-annotation:write', '数据标注写入', 'data-annotation', 'write', '/api/annotation/**', 'POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-dc-read', 'module:data-collection:read', '数据归集读取', 'data-collection', 'read', '/api/data-collection/**', 'GET', 1, 1),
       ('perm-dc-write', 'module:data-collection:write', '数据归集写入', 'data-collection', 'write', '/api/data-collection/**', 'POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-de-read', 'module:data-evaluation:read', '数据评估读取', 'data-evaluation', 'read', '/api/evaluation/**', 'GET', 1, 1),
       ('perm-de-write', 'module:data-evaluation:write', '数据评估写入', 'data-evaluation', 'write', '/api/evaluation/**', 'POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-ds-read', 'module:data-synthesis:read', '数据合成读取', 'data-synthesis', 'read', '/api/synthesis/**', 'GET', 1, 1),
       ('perm-ds-write', 'module:data-synthesis:write', '数据合成写入', 'data-synthesis', 'write', '/api/synthesis/**', 'POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-km-read', 'module:knowledge-management:read', '知识管理读取', 'knowledge-management', 'read', '/api/data-management/knowledge/**', 'GET', 1, 1),
       ('perm-km-write', 'module:knowledge-management:write', '知识管理写入', 'knowledge-management', 'write', '/api/data-management/knowledge/**', 'POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-kb-read', 'module:knowledge-base:read', '知识库读取', 'knowledge-base', 'read', '/api/knowledge-base/**', 'GET', 1, 1),
       ('perm-kb-write', 'module:knowledge-base:write', '知识库写入', 'knowledge-base', 'write', '/api/knowledge-base/**', 'POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-om-read', 'module:operator-market:read', '算子市场读取', 'operator-market', 'read', '/api/operator-market/**', 'GET', 1, 1),
       ('perm-om-write', 'module:operator-market:write', '算子市场写入', 'operator-market', 'write', '/api/operator-market/**', 'POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-orch-read', 'module:orchestration:read', '流程编排读取', 'orchestration', 'read', '/api/orchestration/**', 'GET', 1, 1),
       ('perm-orch-write', 'module:orchestration:write', '流程编排写入', 'orchestration', 'write', '/api/orchestration/**', 'POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-agent-use', 'module:agent:use', '对话助手使用', 'agent', 'use', '/chat/**', 'GET', 1, 1),
       ('perm-content-use', 'module:content-generation:use', '内容生成功能使用', 'content-generation', 'use', '/api/content-generation/**', 'POST,PUT,PATCH', 1, 1),
       ('perm-user-manage', 'system:user:manage', '用户管理', 'system', 'manage-user', '/api/auth/users/**', 'GET,POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-role-manage', 'system:role:manage', '角色管理', 'system', 'manage-role', '/api/auth/roles/**', 'GET,POST,PUT,PATCH,DELETE', 1, 1),
       ('perm-perm-manage', 'system:permission:manage', '权限管理', 'system', 'manage-permission', '/api/auth/permissions/**', 'GET,POST,PUT,PATCH,DELETE', 1, 1);

-- 管理员拥有所有权限
INSERT IGNORE INTO t_auth_role_permissions (role_id, permission_id)
SELECT 'role-admin', p.id
FROM t_auth_permissions p;

-- 数据运营拥有业务模块读写权限（不含系统管理）
INSERT IGNORE INTO t_auth_role_permissions (role_id, permission_id)
SELECT 'role-data-editor', p.id
FROM t_auth_permissions p
WHERE p.permission_code IN (
    'module:data-management:read', 'module:data-management:write',
    'module:data-annotation:read', 'module:data-annotation:write',
    'module:data-collection:read', 'module:data-collection:write',
    'module:data-evaluation:read', 'module:data-evaluation:write',
    'module:data-synthesis:read', 'module:data-synthesis:write',
    'module:knowledge-management:read', 'module:knowledge-management:write',
    'module:knowledge-base:read', 'module:knowledge-base:write',
    'module:operator-market:read', 'module:operator-market:write',
    'module:orchestration:read', 'module:orchestration:write',
    'module:agent:use', 'module:content-generation:use'
);

-- 知识用户拥有知识相关权限及必要数据读取权限
INSERT IGNORE INTO t_auth_role_permissions (role_id, permission_id)
SELECT 'role-knowledge-user', p.id
FROM t_auth_permissions p
WHERE p.permission_code IN (
    'module:data-management:read',
    'module:knowledge-management:read', 'module:knowledge-management:write',
    'module:knowledge-base:read', 'module:knowledge-base:write',
    'module:agent:use'
);

-- =============================================
-- 用户角色初始化（绑定到已有 users）
-- =============================================
INSERT IGNORE INTO t_auth_user_roles (user_id, role_id)
SELECT u.id, 'role-admin'
FROM users u
WHERE u.username = 'admin';

INSERT IGNORE INTO t_auth_user_roles (user_id, role_id)
SELECT u.id, 'role-knowledge-user'
FROM users u
WHERE u.username = 'knowledge_user';

