-- Migration 155: Links module permissions

INSERT INTO permissions (code, description, category) VALUES
('links.read', 'View links and endpoint actions', 'links'),
('links.create', 'Create links', 'links'),
('links.update', 'Update links', 'links'),
('links.delete', 'Delete links', 'links'),
('links.use', 'Use links and quick actions', 'links'),
('links.diagnose', 'Run multi-open diagnose actions', 'links')
ON CONFLICT (code) DO NOTHING;

INSERT INTO group_permissions (group_id, permission_id)
SELECT g.id, p.id
FROM groups g
CROSS JOIN permissions p
WHERE g.name = 'Administrators'
  AND p.category = 'links'
ON CONFLICT DO NOTHING;

INSERT INTO group_permissions (group_id, permission_id)
SELECT g.id, p.id
FROM groups g
CROSS JOIN permissions p
WHERE g.name = 'Managers'
  AND p.code IN ('links.read', 'links.create', 'links.update', 'links.use', 'links.diagnose')
ON CONFLICT DO NOTHING;

INSERT INTO group_permissions (group_id, permission_id)
SELECT g.id, p.id
FROM groups g
CROSS JOIN permissions p
WHERE g.name = 'Technicians'
  AND p.code IN ('links.read', 'links.use', 'links.diagnose')
ON CONFLICT DO NOTHING;

INSERT INTO group_permissions (group_id, permission_id)
SELECT g.id, p.id
FROM groups g
CROSS JOIN permissions p
WHERE g.name = 'Viewers'
  AND p.code = 'links.read'
ON CONFLICT DO NOTHING;
