-- 银行卡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.bankcard', '银行卡OCR识别', 'ocr'
FROM dual
WHERE NOT EXISTS (SELECT 1 FROM permission WHERE permission_code = 'ocr.bankcard');

UPDATE permission
SET permission_name = '银行卡OCR识别',
    module = 'ocr'
WHERE permission_code = 'ocr.bankcard';

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.bankcard'
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.bankcard', '平台银行卡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.bankcard'
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
  );

