-- Backfill invoice error finder permissions and group grants on environments
-- where migration 1007 did not run completely.

INSERT INTO permissions (code, description, category) VALUES
('invoice_error_finder.view', 'View invoice error finder dashboard and issues', 'invoice_error_finder'),
('invoice_error_finder.run_import', 'Trigger invoice/error data imports', 'invoice_error_finder'),
('invoice_error_finder.analyze', 'Run invoice error detection analysis', 'invoice_error_finder'),
('invoice_error_finder.update_status', 'Update issue status and assignee', 'invoice_error_finder'),
('invoice_error_finder.create_sag', 'Create/link sag from invoice error issue', 'invoice_error_finder'),
('invoice_error_finder.create_ordre_draft', 'Create ordre draft from invoice error issue', 'invoice_error_finder'),
('invoice_error_finder.ignore', 'Ignore invoice error issues', 'invoice_error_finder'),
('invoice_error_finder.admin', 'Administer invoice error finder settings', 'invoice_error_finder')
ON CONFLICT (code) DO NOTHING;

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

INSERT INTO group_permissions (group_id, permission_id)
SELECT g.id, p.id
FROM groups g
JOIN permissions p ON p.code IN (
    'invoice_error_finder.view',
    'invoice_error_finder.update_status',
    'invoice_error_finder.create_sag',
    'invoice_error_finder.create_ordre_draft'
)
WHERE g.name = 'Technicians'
ON CONFLICT DO NOTHING;

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