-- CRM Contact permissions (run once on deploy)
-- Guard: web (matches Spatie usage in this project)

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

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

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

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

-- Assign to Admin role (adjust role name/id if needed)
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-contact.view',
    'admin.crm-contact.create',
    'admin.crm-contact.edit',
    'admin.crm-contact.delete'
  )
  AND NOT EXISTS (
    SELECT 1 FROM role_has_permissions rhp
    WHERE rhp.permission_id = p.id AND rhp.role_id = r.id
  );
