-- Slice 8b-5 · Callout Playbook perms

-- CalloutPlaybooks authoring: Admin + Executive
INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'CalloutPlaybooks', a.act, 0, NOW()
FROM (
    SELECT 'index' AS act UNION ALL SELECT 'edit'
    UNION ALL SELECT 'createAj' UNION ALL SELECT 'updateHeaderAj' UNION ALL SELECT 'setActiveAj'
    UNION ALL SELECT 'upsertSlaAj' UNION ALL SELECT 'deleteSlaAj'
    UNION ALL SELECT 'addEscalationAj' UNION ALL SELECT 'deleteEscalationAj'
) a
CROSS JOIN user_groups g
WHERE g.user_group_name IN ('Administrator','Executive')
  AND NOT EXISTS (SELECT 1 FROM user_groups_perms p WHERE p.user_group_id = g.c0d AND p.controller_allowed = 'CalloutPlaybooks' AND p.action_allowed = a.act);

-- Read-only for FM, PM, PC, FS
INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'CalloutPlaybooks', a.act, 0, NOW()
FROM (SELECT 'index' AS act UNION ALL SELECT 'edit') a
CROSS JOIN user_groups g
WHERE g.user_group_name IN ('Finance Manager','Project Manager','Projects Coordinator','Field Supervisor')
  AND NOT EXISTS (SELECT 1 FROM user_groups_perms p WHERE p.user_group_id = g.c0d AND p.controller_allowed = 'CalloutPlaybooks' AND p.action_allowed = a.act);

-- SpCallouts project-scoped playbook attachment: PC + PM + Admin can attach; FS + FM + Exec can view
INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'SpCallouts', a.act, 0, NOW()
FROM (SELECT 'playbook' AS act UNION ALL SELECT 'attachAj') a
CROSS JOIN user_groups g
WHERE g.user_group_name IN ('Projects Coordinator','Project Manager','Administrator')
  AND NOT EXISTS (SELECT 1 FROM user_groups_perms p WHERE p.user_group_id = g.c0d AND p.controller_allowed = 'SpCallouts' AND p.action_allowed = a.act);

INSERT INTO user_groups_perms (user_group_id, controller_allowed, action_allowed, created_by, created_on)
SELECT g.c0d, 'SpCallouts', 'playbook', 0, NOW()
FROM user_groups g
WHERE g.user_group_name IN ('Field Supervisor','Finance Manager','Executive')
  AND NOT EXISTS (SELECT 1 FROM user_groups_perms p WHERE p.user_group_id = g.c0d AND p.controller_allowed = 'SpCallouts' AND p.action_allowed = 'playbook');
