START TRANSACTION;

INSERT IGNORE INTO permissions (code, name, module, created_at) VALUES
('production_tools.access', 'Akses Workspace Production Tools', 'production_tools', NOW());

UPDATE permissions
SET name = 'Akses Workspace Production Tools',
    module = 'production_tools'
WHERE code = 'production_tools.access';

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT DISTINCT rp.role_id, target.id
FROM role_permissions rp
INNER JOIN permissions source ON source.id = rp.permission_id
INNER JOIN permissions target ON target.code = 'production_tools.access'
WHERE source.code IN (
  'digital_production.view',
  'digital_production.create',
  'digital_production.edit',
  'digital_production.close_shift',
  'digital_production.manage_click_rules'
);

INSERT IGNORE INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
INNER JOIN permissions p ON p.code = 'production_tools.access'
WHERE r.code IN ('owner', 'admin', 'kepala_toko');

COMMIT;
