-- Migration 026: Add Ticket System Permissions
-- Description: Adds ticket-related permissions to auth system
-- Date: 2025-12-15

-- Add ticket permissions
INSERT INTO permissions (code, description, category) VALUES
('tickets.view', 'View tickets', 'tickets'),
('tickets.create', 'Create tickets', 'tickets'),
('tickets.edit', 'Edit tickets', 'tickets'),
('tickets.delete', 'Delete tickets', 'tickets'),
('tickets.assign', 'Assign tickets to users', 'tickets'),
('tickets.worklog.create', 'Create worklog entries', 'tickets'),
('tickets.worklog.approve', 'Approve worklog for billing', 'tickets'),
('tickets.billing.export', 'Export billable worklog to e-conomic', 'tickets'),
('tickets.prepaid.manage', 'Manage prepaid cards (klippekort)', 'tickets')
ON CONFLICT (code) DO NOTHING;

-- Assign ticket permissions to Administrators group (all permissions)
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 = 'tickets'
ON CONFLICT DO NOTHING;

-- Assign ticket permissions to Managers group
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 (
    'tickets.view', 'tickets.create', 'tickets.edit', 'tickets.assign',
    'tickets.worklog.approve', 'tickets.billing.export', 'tickets.prepaid.manage'
)
ON CONFLICT DO NOTHING;

-- Assign ticket permissions to Technicians group
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 (
    'tickets.view', 'tickets.create', 'tickets.edit', 'tickets.worklog.create'
)
ON CONFLICT DO NOTHING;

-- Assign ticket view permission to Viewers group
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 = 'tickets.view'
ON CONFLICT DO NOTHING;

-- Verify migration
SELECT 'Ticket permissions added successfully' AS status,
       COUNT(*) AS ticket_permissions_count
FROM permissions
WHERE category = 'tickets';
