SET NAMES utf8mb4;

INSERT INTO permissions (code, name)
SELECT 'shops.scope.view', 'Consulter les boutiques de son périmètre local'
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE code = 'shops.scope.view');

INSERT INTO permissions (code, name)
SELECT 'users.local.manage', 'Gérer localement les agents d’agence'
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE code = 'users.local.manage');

INSERT INTO permissions (code, name)
SELECT 'orders.view', 'Consulter les commandes de son périmètre'
WHERE NOT EXISTS (SELECT 1 FROM permissions WHERE code = 'orders.view');

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
INNER JOIN permissions p ON p.code = 'backoffice.access'
WHERE r.code IN ('agency_manager', 'shop_manager')
  AND NOT EXISTS (
      SELECT 1
      FROM role_permissions rp
      WHERE rp.role_id = r.id
        AND rp.permission_id = p.id
  );

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
INNER JOIN permissions p ON p.code = 'shops.scope.view'
WHERE r.code IN ('agency_manager', 'shop_manager')
  AND NOT EXISTS (
      SELECT 1
      FROM role_permissions rp
      WHERE rp.role_id = r.id
        AND rp.permission_id = p.id
  );

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
INNER JOIN permissions p ON p.code = 'users.local.manage'
WHERE r.code IN ('agency_manager', 'shop_manager')
  AND NOT EXISTS (
      SELECT 1
      FROM role_permissions rp
      WHERE rp.role_id = r.id
        AND rp.permission_id = p.id
  );

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
INNER JOIN permissions p ON p.code = 'orders.view'
WHERE r.code IN ('agency_manager', 'shop_manager')
  AND NOT EXISTS (
      SELECT 1
      FROM role_permissions rp
      WHERE rp.role_id = r.id
        AND rp.permission_id = p.id
  );
