-- Sale module (Sales & CRM workspace)
-- Run against your ERP database (e.g. erp_foundation)
-- Safe to re-run: uses INSERT ... WHERE NOT EXISTS
-- Tables will be added as CRM and sales sub-features ship.

INSERT INTO `permissions` (`group`, `slug`, `label`, `is_system`, `created_at`)
SELECT 'sale', 'sale.view', 'View Sales & CRM Dashboard', 1, NOW()
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `permissions` WHERE `slug` = 'sale.view');

-- Grant sale permissions to Administrator role
INSERT INTO `role_permissions` (`role_id`, `permission_id`, `created_at`)
SELECT r.id, p.id, NOW()
FROM `roles` r
CROSS JOIN `permissions` p
WHERE r.slug = 'administrator'
  AND p.slug LIKE 'sale.%'
  AND NOT EXISTS (
      SELECT 1 FROM `role_permissions` rp
      WHERE rp.role_id = r.id AND rp.permission_id = p.id
  );
