-- CRM Ticket + Followup permissions (run once on deploy)
-- Guard: web

INSERT INTO permissions (name, guard_name, group_name, created_at, updated_at)
SELECT 'admin.crm-ticket.view', 'web', 'CRM Ticket', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE name = 'admin.crm-ticket.view' AND guard_name = 'web');

INSERT INTO permissions (name, guard_name, group_name, created_at, updated_at)
SELECT 'admin.crm-ticket.create', 'web', 'CRM Ticket', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE name = 'admin.crm-ticket.create' AND guard_name = 'web');

INSERT INTO permissions (name, guard_name, group_name, created_at, updated_at)
SELECT 'admin.crm-ticket.edit', 'web', 'CRM Ticket', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE name = 'admin.crm-ticket.edit' AND guard_name = 'web');

INSERT INTO permissions (name, guard_name, group_name, created_at, updated_at)
SELECT 'admin.crm-ticket.delete', 'web', 'CRM Ticket', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE name = 'admin.crm-ticket.delete' AND guard_name = 'web');

INSERT INTO permissions (name, guard_name, group_name, created_at, updated_at)
SELECT 'admin.crm-followup.view', 'web', 'CRM Followup', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE name = 'admin.crm-followup.view' AND guard_name = 'web');

INSERT INTO permissions (name, guard_name, group_name, created_at, updated_at)
SELECT 'admin.crm-followup.create', 'web', 'CRM Followup', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE name = 'admin.crm-followup.create' AND guard_name = 'web');

INSERT INTO permissions (name, guard_name, group_name, created_at, updated_at)
SELECT 'admin.crm-followup.edit', 'web', 'CRM Followup', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE name = 'admin.crm-followup.edit' AND guard_name = 'web');

INSERT INTO permissions (name, guard_name, group_name, created_at, updated_at)
SELECT 'admin.crm-followup.delete', 'web', 'CRM Followup', NOW(), NOW()
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE name = 'admin.crm-followup.delete' AND guard_name = 'web');

INSERT INTO role_has_permissions (permission_id, role_id)
SELECT p.id, r.id
FROM permissions p
CROSS JOIN roles r
WHERE r.name = 'Admin'
  AND p.name IN (
    'admin.crm-ticket.view',
    'admin.crm-ticket.create',
    'admin.crm-ticket.edit',
    'admin.crm-ticket.delete',
    'admin.crm-followup.view',
    'admin.crm-followup.create',
    'admin.crm-followup.edit',
    'admin.crm-followup.delete'
  )
  AND NOT EXISTS (
    SELECT 1 FROM role_has_permissions rhp
    WHERE rhp.permission_id = p.id AND rhp.role_id = r.id
  );
