string('sort', 'name')->toString(); $dir = $request->string('dir', 'asc')->toString() === 'desc' ? 'desc' : 'asc'; $search = $request->string('q')->trim()->toString(); $allowedSort = ['name', 'sam_account_name', 'type', 'members_count', 'description']; if (! in_array($sort, $allowedSort, true)) { $sort = 'name'; } $result = $this->ldapGroups->listGroups($sort, $dir, $search); if ($result['error'] ?? null) { return $this->fail($result['error'], 'service_error', 503); } return $this->ok($result['rows'], $result['meta']); } public function show(string $group): JsonResponse { try { return $this->ok($this->ldapGroups->getGroup($group)); } catch (InvalidArgumentException $e) { return $this->fail($e->getMessage(), 'not_found', 404); } } public function store(Request $request): JsonResponse { $data = $request->validate([ 'name' => ['required', 'string', 'max:255'], 'description' => ['nullable', 'string', 'max:1024'], ]); try { $this->ldapGroups->createGroup($data['name'], $data['description'] ?? null); return $this->ok($this->ldapGroups->getGroup($data['name']), [], 201); } catch (InvalidArgumentException|RuntimeException $e) { return $this->fail($e->getMessage(), 'validation_error', 422); } catch (Throwable) { return $this->fail('Failed to create group.', 'server_error', 500); } } public function addMember(Request $request, string $group): JsonResponse { $data = $request->validate(['username' => ['required', 'string', 'max:100']]); try { $this->ldapGroups->addMember($group, $data['username']); return $this->ok($this->ldapGroups->getGroup($group)); } catch (InvalidArgumentException|RuntimeException $e) { return $this->fail($e->getMessage(), 'validation_error', 422); } catch (Throwable) { return $this->fail('Failed to add member.', 'server_error', 500); } } public function removeMember(string $group, string $username): JsonResponse { try { $this->ldapGroups->removeMember($group, $username); return $this->ok($this->ldapGroups->getGroup($group)); } catch (InvalidArgumentException|RuntimeException $e) { return $this->fail($e->getMessage(), 'validation_error', 422); } catch (Throwable) { return $this->fail('Failed to remove member.', 'server_error', 500); } } }