-- +goose Up
-- +goose StatementBegin

INSERT INTO permissions (code, name, resource, action) VALUES
('qrcode:view', '查看二维码池', 'qrcode', 'view'),
('qrcode:manage', '管理二维码池', 'qrcode', 'manage')
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  resource = VALUES(resource),
  action = VALUES(action);

-- 超级管理员补齐新增权限。
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.code IN ('qrcode:view', 'qrcode:manage')
WHERE r.code = 'super_admin';

-- 客服默认可以查看和维护二维码池。
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.code IN ('qrcode:view', 'qrcode:manage')
WHERE r.code = 'cs';

-- 已拥有客服配置管理权限的角色，迁移后继续拥有二维码池管理能力。
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT DISTINCT rp.role_id, p.id
FROM role_permissions rp
JOIN permissions oldp ON oldp.id = rp.permission_id AND oldp.code = 'chat:manage'
JOIN permissions p ON p.code IN ('qrcode:view', 'qrcode:manage');

-- 已拥有客服群聊查看权限的角色，迁移后继续能进入二维码池查看页。
INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT DISTINCT rp.role_id, p.id
FROM role_permissions rp
JOIN permissions oldp ON oldp.id = rp.permission_id AND oldp.code = 'chat:view'
JOIN permissions p ON p.code = 'qrcode:view';

-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin

DELETE rp FROM role_permissions rp
JOIN permissions p ON p.id = rp.permission_id
WHERE p.code IN ('qrcode:view', 'qrcode:manage');

DELETE FROM permissions WHERE code IN ('qrcode:view', 'qrcode:manage');

-- +goose StatementEnd
