-- Reports module — RBAC for read-only report APIs

INSERT INTO modules (code, name, sort_order, is_active)
VALUES ('REPORTS', 'Reports', 90, true)
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name, sort_order = EXCLUDED.sort_order, is_active = true;

INSERT INTO permissions (module_id, action, is_active)
SELECT m.id, a.action, true
FROM modules m
CROSS JOIN (VALUES ('view'), ('export')) AS a(action)
WHERE m.code = 'REPORTS'
ON CONFLICT (module_id, action) DO UPDATE SET is_active = true;

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.action IN ('view', 'export')
JOIN modules m ON m.id = p.module_id AND m.code = 'REPORTS'
WHERE r.name = 'Super Admin' AND r.deleted_at IS NULL
ON CONFLICT (role_id, permission_id) DO NOTHING;
