SELECT COUNT(*) AS staff_role_count
FROM qipai_roles r
WHERE r.code = 'STAFF' AND r.status = 'ACTIVE' AND r.deleted_at IS NULL
HAVING COUNT(*) = (
  SELECT COUNT(*)
  FROM (
    SELECT granted_role.tenant_id, granted_role.id
    FROM qipai_roles granted_role
    INNER JOIN qipai_role_permissions rp
      ON rp.tenant_id = granted_role.tenant_id AND rp.role_id = granted_role.id
    INNER JOIN qipai_permissions p ON p.id = rp.permission_id
    WHERE granted_role.code = 'STAFF'
      AND granted_role.status = 'ACTIVE'
      AND granted_role.deleted_at IS NULL
      AND p.code IN ('profile.read', 'store.operation.read')
    GROUP BY granted_role.tenant_id, granted_role.id
    HAVING COUNT(DISTINCT p.code) = 2
  ) fully_granted_staff_roles
);
