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.material.export', '导出会议资料包', 'meeting'
FROM dual
WHERE NOT EXISTS (
    SELECT 1
    FROM permission
    WHERE permission_code = 'meeting.material.export'
);

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 = 'meeting.material.export'
WHERE r.role_code = 'PROJECT_OWNER'
  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
  );
