-- 身份证OCR权限：租户域 + 平台域

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, 'ocr.idcard', '身份证OCR识别', 'ocr'
FROM dual
WHERE NOT EXISTS (SELECT 1 FROM permission WHERE permission_code = 'ocr.idcard');

UPDATE permission
SET permission_name = '身份证OCR识别',
    module = 'ocr'
WHERE permission_code = 'ocr.idcard';

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
SELECT
    (SELECT IFNULL(MAX(rp.id), 0) + 1 FROM role_permission rp) AS id,
    r.tenant_id,
    r.id,
    p.id
FROM role r
JOIN permission p ON p.permission_code = 'ocr.idcard'
WHERE r.tenant_id = 1
  AND r.role_code = 'TENANT_ADMIN'
  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 platform_permission (permission_code, permission_name, module)
VALUES ('platform.ocr.idcard', '平台身份证OCR识别', 'platform')
ON DUPLICATE KEY UPDATE
    permission_name = VALUES(permission_name),
    module = VALUES(module);

INSERT INTO platform_role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM platform_role r
JOIN platform_permission p ON p.permission_code = 'platform.ocr.idcard'
WHERE r.role_code = 'PLATFORM_SUPER_ADMIN'
  AND NOT EXISTS (
      SELECT 1
      FROM platform_role_permission rp
      WHERE rp.role_id = r.id
        AND rp.permission_id = p.id
  );

