SET @next_permission_id := (SELECT IFNULL(MAX(id), 0) + 1 FROM permission);
INSERT INTO permission (id, permission_code, permission_name, module)
SELECT @next_permission_id, 'project.key-change-log.read', '查看项目关键变更日志', 'project'
FROM dual
WHERE NOT EXISTS (
    SELECT 1
    FROM permission
    WHERE permission_code = 'project.key-change-log.read'
);

SET @next_permission_id := (SELECT IFNULL(MAX(id), 0) + 1 FROM permission);
INSERT INTO permission (id, permission_code, permission_name, module)
SELECT @next_permission_id, 'meeting.change-log.read', '查看会议变更记录', 'meeting'
FROM dual
WHERE NOT EXISTS (
    SELECT 1
    FROM permission
    WHERE permission_code = 'meeting.change-log.read'
);

SET @next_role_permission_id := (SELECT IFNULL(MAX(id), 0) FROM role_permission);
INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
SELECT
    (@next_role_permission_id := @next_role_permission_id + 1) AS id,
    r.tenant_id,
    r.id AS role_id,
    p.id AS permission_id
FROM role r
JOIN permission p ON p.permission_code = 'project.key-change-log.read'
WHERE r.role_code IN ('TENANT_ADMIN', 'PROJECT_OWNER', 'EXECUTOR', 'AUDITOR', 'FINANCE')
  AND r.is_deleted = 0
  AND NOT EXISTS (
      SELECT 1
      FROM role_permission rp
      WHERE rp.tenant_id = r.tenant_id
        AND rp.role_id = r.id
        AND rp.permission_id = p.id
  );

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
SELECT
    (@next_role_permission_id := @next_role_permission_id + 1) AS id,
    r.tenant_id,
    r.id AS role_id,
    p.id AS permission_id
FROM role r
JOIN permission p ON p.permission_code = 'meeting.change-log.read'
WHERE r.role_code IN ('TENANT_ADMIN', 'PROJECT_OWNER', 'EXECUTOR', 'AUDITOR', 'FINANCE')
  AND r.is_deleted = 0
  AND NOT EXISTS (
      SELECT 1
      FROM role_permission rp
      WHERE rp.tenant_id = r.tenant_id
        AND rp.role_id = r.id
        AND rp.permission_id = p.id
  );
