diff --git a/src/Application/Security/Models/Entities/Client.php b/src/Application/Security/Models/Entities/Client.php index bc092ed..25db84c 100644 --- a/src/Application/Security/Models/Entities/Client.php +++ b/src/Application/Security/Models/Entities/Client.php @@ -77,9 +77,9 @@ final class Client implements Entity $this->updatedAt = new \DateTimeImmutable(); } - public function toggleStatus(): bool + public function setActive(bool $status): bool { - $this->isActive = ! $this->isActive; + $this->isActive = $status; $this->updatedAt = new \DateTimeImmutable(); return $this->isActive; diff --git a/src/Application/Security/Usecases/RegenerateClientSecret/RegenerateClientSecret.php b/src/Application/Security/Usecases/RegenerateClientSecret/RegenerateClientSecret.php index a4c22a1..0328372 100644 --- a/src/Application/Security/Usecases/RegenerateClientSecret/RegenerateClientSecret.php +++ b/src/Application/Security/Usecases/RegenerateClientSecret/RegenerateClientSecret.php @@ -27,7 +27,7 @@ final readonly class RegenerateClientSecret implements Usecase { Assert::isInstanceOf($input, Input::class); - $client = $this->clientRepository->find($input->clientId) ?? throw new ClientNotFoundException(); + $client = $this->clientRepository->find($input->clientId) ?? throw ClientNotFoundException::forClient($input->clientId->value); $newSecret = $this->credentialGenerator->generateSecret(); $client->regenerateSecret($newSecret); diff --git a/src/Application/Security/Usecases/ToggleClientStatus/Input.php b/src/Application/Security/Usecases/ToggleClientStatus/Input.php index 8bd5c1f..bfdeacd 100644 --- a/src/Application/Security/Usecases/ToggleClientStatus/Input.php +++ b/src/Application/Security/Usecases/ToggleClientStatus/Input.php @@ -4,12 +4,13 @@ declare(strict_types=1); namespace Application\Security\Usecases\ToggleClientStatus; -use Application\Security\Models\ValueObjects\Entities\ClientId; +use Application\Security\Models\ValueObjects\ClientIdentifier; final readonly class Input implements \Shared\DDD\Usecase\Input { public function __construct( - public ClientId $clientId, + public ClientIdentifier $clientIdentifier, + public bool $desiredStatus, ) { } } diff --git a/src/Application/Security/Usecases/ToggleClientStatus/ToggleClientStatus.php b/src/Application/Security/Usecases/ToggleClientStatus/SetClientStatus.php similarity index 59% rename from src/Application/Security/Usecases/ToggleClientStatus/ToggleClientStatus.php rename to src/Application/Security/Usecases/ToggleClientStatus/SetClientStatus.php index 458732d..5cdbd16 100644 --- a/src/Application/Security/Usecases/ToggleClientStatus/ToggleClientStatus.php +++ b/src/Application/Security/Usecases/ToggleClientStatus/SetClientStatus.php @@ -13,7 +13,7 @@ use Shared\DDD\Usecase\Usecase; use Webmozart\Assert\Assert; /** @implements Usecase<\Application\Security\Usecases\ToggleClientStatus\Input, \Application\Security\Usecases\ToggleClientStatus\Output> */ -final readonly class ToggleClientStatus implements Usecase +final readonly class SetClientStatus implements Usecase { public function __construct( private ClientRepository $clientRepository, @@ -26,17 +26,22 @@ final readonly class ToggleClientStatus implements Usecase { Assert::isInstanceOf($input, Input::class); - $client = $this->clientRepository->find($input->clientId) ?? throw new ClientNotFoundException(); + $client = $this->clientRepository->findByIdentifier($input->clientIdentifier) + ?? throw ClientNotFoundException::forClient($input->clientIdentifier->value); - $isActive = $client->toggleStatus(); - $this->clientRepository->persist($client); + $changed = $client->isActive !== $input->desiredStatus; + $isActive = $client->setActive($input->desiredStatus); - $this->dispatcher->dispatch(new ClientStatusToggled( - clientId: $client->id, - clientIdentifier: $client->identifier, - isActive: $isActive, - toggledAt: new \DateTimeImmutable(), - )); + if ($changed) { + $this->clientRepository->persist($client); + + $this->dispatcher->dispatch(new ClientStatusToggled( + clientId: $client->id, + clientIdentifier: $client->identifier, + isActive: $isActive, + toggledAt: new \DateTimeImmutable(), + )); + } return new Output( clientId: $client->id, diff --git a/src/Infra/Adapters/Events/LaravelDomainEventDispatcher.php b/src/Infra/Adapters/Events/LaravelDomainEventDispatcher.php new file mode 100644 index 0000000..7110fc8 --- /dev/null +++ b/src/Infra/Adapters/Events/LaravelDomainEventDispatcher.php @@ -0,0 +1,23 @@ +events->dispatch($event); + } +} diff --git a/src/Infra/Providers/DomainServiceProvider.php b/src/Infra/Providers/DomainServiceProvider.php index 8821b4b..6bd4504 100644 --- a/src/Infra/Providers/DomainServiceProvider.php +++ b/src/Infra/Providers/DomainServiceProvider.php @@ -13,7 +13,9 @@ use Infra\Adapters\Directories\EloquentEmployeeDirectory; use Infra\Adapters\Directories\EloquentIncoCompositionDirectory; use Infra\Adapters\Directories\EloquentIncoSheetDirectory; use Infra\Adapters\Directories\EloquentIncoShortSheetDirectory; +use Infra\Adapters\Events\LaravelDomainEventDispatcher; use Infra\Usecase\LaravelExecutor; +use Shared\DDD\Event\DomainEventDispatcher; use Shared\DDD\Usecase\Builder\UsecaseExecutor; class DomainServiceProvider extends ServiceProvider @@ -25,6 +27,7 @@ class DomainServiceProvider extends ServiceProvider $this->app->bind(IncoSheetDirectory::class, EloquentIncoSheetDirectory::class); $this->app->bind(IncoShortSheetDirectory::class, EloquentIncoShortSheetDirectory::class); $this->app->bind(IncoCompositionDirectory::class, EloquentIncoCompositionDirectory::class); + $this->app->bind(DomainEventDispatcher::class, LaravelDomainEventDispatcher::class); $this->app->singleton(UsecaseExecutor::class, LaravelExecutor::class); } } diff --git a/src/Presentation/Console/Commands/ToggleClientStatusCommand.php b/src/Presentation/Console/Commands/ToggleClientStatusCommand.php new file mode 100644 index 0000000..7f71bac --- /dev/null +++ b/src/Presentation/Console/Commands/ToggleClientStatusCommand.php @@ -0,0 +1,163 @@ +mustSuggestArgumentValuesFor('identifier')) { + $clients = $this->clientRepository->findAll(Pagination::ofOffsetAndLimit(0, 100)); + + /** @var list $items */ + $items = array_map( + static fn (Client $client): Suggestion => new Suggestion( + value: $client->identifier->value, + description: sprintf('%s (%s)', $client->name->value, $client->isActive ? 'Active' : 'Inactive'), + ), + $clients->getItems(), + ); + $suggestions->suggestValues($items); + } + + if ($input->mustSuggestArgumentValuesFor('status')) { + $suggestions->suggestValues([ + new Suggestion('activate', 'Activate the client'), + new Suggestion('deactivate', 'Deactivate the client'), + ]); + } + } + + public function handle( + SetClientStatus $usecase, + UsecaseExecutor $executor, + ): int { + $identifierString = $this->resolveIdentifier(); + + if ($identifierString === null) { + return self::FAILURE; + } + + try { + $clientIdentifier = $this->parseClientIdentifier($identifierString); + $desiredStatus = $this->resolveDesiredStatus($clientIdentifier); + $input = new Input($clientIdentifier, $desiredStatus); + + $view = UsecaseBuilder::using($executor) + ->do($usecase) + ->from($input) + ->with(new SetClientStatusPresenter()) + ->run(); + + $this->info($view->message); + + return self::SUCCESS; + } catch (ClientNotFoundException | \InvalidArgumentException $e) { + $this->error($e->getMessage()); + + return self::FAILURE; + } + } + + private function resolveIdentifier(): ?string + { + $raw = $this->argument('identifier'); + + if ($raw !== null) { + return (string) $raw; + } + + $clients = $this->clientRepository->findAll(Pagination::ofOffsetAndLimit(0, 50)); + $items = $clients->getItems(); + + if ($items === []) { + $this->error('No clients found in the database.'); + + return null; + } + + $choices = []; + foreach ($items as $client) { + $choices[$client->identifier->value] = sprintf( + '%s (%s) - %s', + $client->name->value, + $client->isActive ? 'Active' : 'Inactive', + $client->identifier->value, + ); + } + + $selectedDisplay = $this->choice('Which client would you like to update?', array_values($choices)); + + return (string) array_search($selectedDisplay, $choices, true); + } + + /** + * @throws \InvalidArgumentException + */ + private function parseClientIdentifier(string $value): ClientIdentifier + { + try { + return new ClientIdentifier($value); + } catch (\InvalidArgumentException) { + throw new \InvalidArgumentException("Invalid client identifier '{$value}'. Expected a valid client identifier."); + } + } + + private function resolveDesiredStatus(ClientIdentifier $clientIdentifier): bool + { + $status = $this->argument('status') !== null ? (string) $this->argument('status') : null; + + return match ($status) { + 'activate' => true, + 'deactivate' => false, + null => $this->resolveToggledStatus($clientIdentifier), + default => throw new \InvalidArgumentException("Invalid status '{$status}'. Expected 'activate' or 'deactivate'."), + }; + } + + private function resolveToggledStatus(ClientIdentifier $clientIdentifier): bool + { + $client = $this->clientRepository->findByIdentifier($clientIdentifier) + ?? throw ClientNotFoundException::forClient($clientIdentifier->value); + + return ! $client->isActive; + } +} diff --git a/src/Presentation/Console/Presenters/Clients/SetClientStatusPresenter.php b/src/Presentation/Console/Presenters/Clients/SetClientStatusPresenter.php new file mode 100644 index 0000000..449ba6e --- /dev/null +++ b/src/Presentation/Console/Presenters/Clients/SetClientStatusPresenter.php @@ -0,0 +1,32 @@ + */ +final readonly class SetClientStatusPresenter implements Presenter +{ + #[\Override] + public function present(UsecaseOutput $output): object + { + Assert::isInstanceOf($output, Output::class); + + $statusLabel = $output->isActive ? 'Active' : 'Inactive'; + $message = "Client '{$output->clientName->value}' (ID: {$output->clientId->value}) is now {$statusLabel}."; + + return new ToggleClientStatusView( + id: $output->clientId->value, + name: $output->clientName->value, + identifier: $output->clientIdentifier->value, + isActive: $output->isActive, + statusLabel: $statusLabel, + message: $message, + ); + } +} diff --git a/src/Presentation/Console/Presenters/Clients/ToggleClientStatusView.php b/src/Presentation/Console/Presenters/Clients/ToggleClientStatusView.php new file mode 100644 index 0000000..8323d07 --- /dev/null +++ b/src/Presentation/Console/Presenters/Clients/ToggleClientStatusView.php @@ -0,0 +1,18 @@ +delete(); - // WHEN & THEN + // WHEN $this->artisan('client:list') + // THEN ->expectsOutput('No clients found.') ->assertSuccessful(); }); - it('lists clients in a table when clients exist', function (): void { + it('outputs table of clients when clients exist', function (): void { // GIVEN + /** @var \Tests\TestCase $this */ ApiClient::query()->delete(); $client1 = ApiClient::query()->create([ 'id' => (string) Uuid::uuid7(), - 'name' => 'Gateway Alpha', + 'name' => 'Production Gateway', 'identifier' => 'arcadia_id_' . str_repeat('a', 32), 'secret' => 'arcadia_sec_' . str_repeat('b', 86), 'is_active' => true, @@ -35,23 +38,23 @@ describe('ListClientsCommand', function (): void { $client2 = ApiClient::query()->create([ 'id' => (string) Uuid::uuid7(), - 'name' => 'Gateway Beta', + 'name' => 'Backup Gateway', 'identifier' => 'arcadia_id_' . str_repeat('c', 32), 'secret' => 'arcadia_sec_' . str_repeat('d', 86), 'is_active' => false, ]); - // WHEN & THEN + // WHEN $this->artisan('client:list') + // THEN ->expectsTable( - ['ID', 'Name', 'Identifier', 'Status', 'Created At', 'Updated At'], + ['ID', 'Name', 'Identifier', 'Status', 'Last Updated At'], [ [ (string) $client1->id, (string) $client1->name->value, (string) $client1->identifier->value, 'Active', - $client1->created_at->format('Y-m-d H:i:s'), $client1->updated_at->format('Y-m-d H:i:s'), ], [ @@ -59,7 +62,6 @@ describe('ListClientsCommand', function (): void { (string) $client2->name->value, (string) $client2->identifier->value, 'Inactive', - $client2->created_at->format('Y-m-d H:i:s'), $client2->updated_at->format('Y-m-d H:i:s'), ], ] @@ -70,6 +72,7 @@ describe('ListClientsCommand', function (): void { it('respects pagination options', function (): void { // GIVEN + /** @var \Tests\TestCase $this */ ApiClient::query()->delete(); for ($i = 1; $i <= 3; $i++) { @@ -82,8 +85,9 @@ describe('ListClientsCommand', function (): void { ]); } - // WHEN & THEN + // WHEN $this->artisan('client:list', ['--page' => '2', '--per-page' => '2']) + // THEN ->expectsOutput('Showing page 2/2 (Total: 3 client(s))') ->assertSuccessful(); }); diff --git a/tests/Feature/Console/Commands/ToggleClientStatusCommandTest.php b/tests/Feature/Console/Commands/ToggleClientStatusCommandTest.php new file mode 100644 index 0000000..517770c --- /dev/null +++ b/tests/Feature/Console/Commands/ToggleClientStatusCommandTest.php @@ -0,0 +1,192 @@ +artisan('client:toggle-status', ['identifier' => $invalidId]) + // THEN + ->expectsOutput("Invalid client identifier '{$invalidId}'. Expected a valid client identifier.") + ->assertFailed(); + }); + + it('errors when client does not exist', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + $nonExistentId = 'arcadia_id_' . str_repeat('9', 32); + + // WHEN + $this->artisan('client:toggle-status', ['identifier' => $nonExistentId]) + // THEN + ->expectsOutput("Client '{$nonExistentId}' not found.") + ->assertFailed(); + }); + + it('toggles an active client to inactive when no status argument is passed', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + $client = ApiClient::query()->create([ + 'id' => (string) Uuid::uuid7(), + 'name' => 'Production Gateway', + 'identifier' => 'arcadia_id_' . str_repeat('a', 32), + 'secret' => 'arcadia_sec_' . str_repeat('b', 86), + 'is_active' => true, + ]); + + // WHEN + $this->artisan('client:toggle-status', ['identifier' => (string) $client->identifier->value]) + // THEN + ->expectsOutput("Client 'Production Gateway' (ID: {$client->id}) is now Inactive.") + ->assertSuccessful(); + + $client->refresh(); + expect($client->is_active)->toBeFalse(); + }); + + it('toggles an inactive client to active when no status argument is passed', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + $client = ApiClient::query()->create([ + 'id' => (string) Uuid::uuid7(), + 'name' => 'Backup Gateway', + 'identifier' => 'arcadia_id_' . str_repeat('c', 32), + 'secret' => 'arcadia_sec_' . str_repeat('d', 86), + 'is_active' => false, + ]); + + // WHEN + $this->artisan('client:toggle-status', ['identifier' => (string) $client->identifier->value]) + // THEN + ->expectsOutput("Client 'Backup Gateway' (ID: {$client->id}) is now Active.") + ->assertSuccessful(); + + $client->refresh(); + expect($client->is_active)->toBeTrue(); + }); + + it('activates an inactive client when activate status is passed', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + $client = ApiClient::query()->create([ + 'id' => (string) Uuid::uuid7(), + 'name' => 'Special Gateway', + 'identifier' => 'arcadia_id_' . str_repeat('e', 32), + 'secret' => 'arcadia_sec_' . str_repeat('f', 86), + 'is_active' => false, + ]); + + // WHEN + $this->artisan('client:toggle-status', ['identifier' => (string) $client->identifier->value, 'status' => 'activate']) + // THEN + ->expectsOutput("Client 'Special Gateway' (ID: {$client->id}) is now Active.") + ->assertSuccessful(); + + $client->refresh(); + expect($client->is_active)->toBeTrue(); + }); + + it('deactivates an active client when deactivate status is passed', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + $client = ApiClient::query()->create([ + 'id' => (string) Uuid::uuid7(), + 'name' => 'Special Gateway', + 'identifier' => 'arcadia_id_' . str_repeat('g', 32), + 'secret' => 'arcadia_sec_' . str_repeat('h', 86), + 'is_active' => true, + ]); + + // WHEN + $this->artisan('client:toggle-status', ['identifier' => (string) $client->identifier->value, 'status' => 'deactivate']) + // THEN + ->expectsOutput("Client 'Special Gateway' (ID: {$client->id}) is now Inactive.") + ->assertSuccessful(); + + $client->refresh(); + expect($client->is_active)->toBeFalse(); + }); + + it('errors when an invalid status is passed', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + $identifier = 'arcadia_id_' . str_repeat('z', 32); + ApiClient::query()->create([ + 'id' => (string) Uuid::uuid7(), + 'name' => 'Some Gateway', + 'identifier' => $identifier, + 'secret' => 'arcadia_sec_' . str_repeat('z', 86), + 'is_active' => true, + ]); + + // WHEN + $this->artisan('client:toggle-status', ['identifier' => $identifier, 'status' => 'unknown']) + // THEN + ->expectsOutput("Invalid status 'unknown'. Expected 'activate' or 'deactivate'.") + ->assertFailed(); + }); + + it('provides autocompletion suggestions for identifier', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + ApiClient::query()->delete(); + + ApiClient::query()->create([ + 'id' => (string) Uuid::uuid7(), + 'name' => 'Production Gateway', + 'identifier' => 'arcadia_id_' . str_repeat('a', 32), + 'secret' => 'arcadia_sec_' . str_repeat('b', 86), + 'is_active' => true, + ]); + + ApiClient::query()->create([ + 'id' => (string) Uuid::uuid7(), + 'name' => 'Backup Gateway', + 'identifier' => 'arcadia_id_' . str_repeat('c', 32), + 'secret' => 'arcadia_sec_' . str_repeat('d', 86), + 'is_active' => false, + ]); + + /** @var ToggleClientStatusCommand $command */ + $command = app(ToggleClientStatusCommand::class); + $tester = new CommandCompletionTester($command); + + // WHEN + $suggestions = $tester->complete(['']); + + // THEN + expect($suggestions) + ->toContain('arcadia_id_' . str_repeat('a', 32)) + ->toContain('arcadia_id_' . str_repeat('c', 32)); + }); + + it('provides autocompletion suggestions for status argument', function (): void { + // GIVEN + /** @var \Tests\TestCase $this */ + /** @var ToggleClientStatusCommand $command */ + $command = app(ToggleClientStatusCommand::class); + $tester = new CommandCompletionTester($command); + $someId = 'arcadia_id_' . str_repeat('1', 32); + + // WHEN + $suggestions = $tester->complete([$someId, '']); + + // THEN + expect($suggestions) + ->toContain('activate') + ->toContain('deactivate'); + }); +}); diff --git a/tests/Integration/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php b/tests/Integration/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php new file mode 100644 index 0000000..8bc2a55 --- /dev/null +++ b/tests/Integration/Infra/Adapters/Events/LaravelDomainEventDispatcherTest.php @@ -0,0 +1,34 @@ +expects('dispatch') + ->once() + ->with($event); + + // WHEN + $dispatcher->dispatch($event); + + // THEN + expect(true)->toBeTrue(); + }); +}); diff --git a/tests/Unit/Application/Security/Usecases/ToggleClientStatus/ToggleClientStatusTest.php b/tests/Unit/Application/Security/Usecases/ToggleClientStatus/ToggleClientStatusTest.php index e8ff624..12e3d81 100644 --- a/tests/Unit/Application/Security/Usecases/ToggleClientStatus/ToggleClientStatusTest.php +++ b/tests/Unit/Application/Security/Usecases/ToggleClientStatus/ToggleClientStatusTest.php @@ -13,33 +13,33 @@ use Application\Security\Models\ValueObjects\ClientSecret; use Application\Security\Models\ValueObjects\Entities\ClientId; use Application\Security\Usecases\ToggleClientStatus\Input; use Application\Security\Usecases\ToggleClientStatus\Output; -use Application\Security\Usecases\ToggleClientStatus\ToggleClientStatus; +use Application\Security\Usecases\ToggleClientStatus\SetClientStatus; use Infra\Adapters\Repositories\InMemoryClientRepository; use Mockery; use Ramsey\Uuid\Uuid; use Shared\DDD\Event\DomainEventDispatcher; covers( - ToggleClientStatus::class, + SetClientStatus::class, Input::class, Output::class, ); -describe('ToggleClientStatus Usecase Unit Tests', function (): void { +describe('SetClientStatus Usecase', function (): void { $repository = new InMemoryClientRepository(); beforeEach(function () use ($repository): void { $repository->clear(); }); - it('toggles an active client to inactive and dispatches event', function () use ($repository): void { + it('deactivates an active client and dispatches event', function () use ($repository): void { // GIVEN $dispatcher = Mockery::mock(DomainEventDispatcher::class); - $usecase = new ToggleClientStatus($repository, $dispatcher); + $usecase = new SetClientStatus($repository, $dispatcher); $clientId = new ClientId(Uuid::uuid7()); $identifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32)); - $name = new ClientName('Test Gateway'); + $name = new ClientName('Test Gateway 1'); $secret = new ClientSecret('arcadia_sec_' . str_repeat('b', 86)); $client = Client::hydrate( @@ -60,7 +60,7 @@ describe('ToggleClientStatus Usecase Unit Tests', function (): void { && $event->clientId->equals($clientId) && $event->isActive === false); - $input = new Input($clientId); + $input = new Input($identifier, desiredStatus: false); // WHEN $result = $usecase->execute($input); @@ -76,10 +76,10 @@ describe('ToggleClientStatus Usecase Unit Tests', function (): void { expect($saved?->isActive)->toBeFalse(); }); - it('toggles an inactive client to active and dispatches event', function () use ($repository): void { + it('activates an inactive client and dispatches event', function () use ($repository): void { // GIVEN $dispatcher = Mockery::mock(DomainEventDispatcher::class); - $usecase = new ToggleClientStatus($repository, $dispatcher); + $usecase = new SetClientStatus($repository, $dispatcher); $clientId = new ClientId(Uuid::uuid7()); $identifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32)); @@ -104,7 +104,7 @@ describe('ToggleClientStatus Usecase Unit Tests', function (): void { && $event->clientId->equals($clientId) && $event->isActive === true); - $input = new Input($clientId); + $input = new Input($identifier, desiredStatus: true); // WHEN $result = $usecase->execute($input); @@ -120,13 +120,132 @@ describe('ToggleClientStatus Usecase Unit Tests', function (): void { it('throws ClientNotFoundException when client does not exist', function () use ($repository): void { // GIVEN $dispatcher = Mockery::mock(DomainEventDispatcher::class); - $usecase = new ToggleClientStatus($repository, $dispatcher); + $usecase = new SetClientStatus($repository, $dispatcher); - $clientId = new ClientId(Uuid::uuid7()); - $input = new Input($clientId); + $identifier = new ClientIdentifier('arcadia_id_' . str_repeat('9', 32)); + $input = new Input($identifier, desiredStatus: true); // WHEN & THEN expect(fn () => $usecase->execute($input)) ->toThrow(ClientNotFoundException::class); }); + + it('does not dispatch event when status is already the desired value', function () use ($repository): void { + // GIVEN + $dispatcher = Mockery::mock(DomainEventDispatcher::class); + $usecase = new SetClientStatus($repository, $dispatcher); + + $clientId = new ClientId(Uuid::uuid7()); + $identifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32)); + $name = new ClientName('Already Active Client'); + $secret = new ClientSecret('arcadia_sec_' . str_repeat('b', 86)); + + $client = Client::hydrate( + id: $clientId, + name: $name, + identifier: $identifier, + secret: $secret, + isActive: true, + createdAt: new \DateTimeImmutable(), + updatedAt: new \DateTimeImmutable(), + ); + + $repository->add($client); + + $dispatcher->expects('dispatch')->never(); + + $input = new Input($identifier, desiredStatus: true); + + // WHEN + $result = $usecase->execute($input); + + // THEN + expect($result)->toBeInstanceOf(Output::class) + ->and($result->isActive)->toBeTrue(); + + $saved = $repository->find($clientId); + expect($saved?->isActive)->toBeTrue(); + }); + + it('deactivates an active client when desiredStatus is false', function () use ($repository): void { + // GIVEN + $dispatcher = Mockery::mock(DomainEventDispatcher::class); + $usecase = new SetClientStatus($repository, $dispatcher); + + $clientId = new ClientId(Uuid::uuid7()); + $identifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32)); + $name = new ClientName('Test Gateway 3'); + $secret = new ClientSecret('arcadia_sec_' . str_repeat('b', 86)); + + $client = Client::hydrate( + id: $clientId, + name: $name, + identifier: $identifier, + secret: $secret, + isActive: true, + createdAt: new \DateTimeImmutable(), + updatedAt: new \DateTimeImmutable(), + ); + + $repository->add($client); + + $dispatcher->expects('dispatch') + ->once() + ->withArgs(fn ($event): bool => $event instanceof ClientStatusToggled + && $event->clientId->equals($clientId) + && $event->isActive === false); + + $input = new Input($identifier, desiredStatus: false); + + // WHEN + $result = $usecase->execute($input); + + // THEN + expect($result)->toBeInstanceOf(Output::class) + ->and($result->isActive)->toBeFalse(); + + $saved = $repository->find($clientId); + expect($saved?->isActive)->toBeFalse(); + }); + + it('activates an inactive client when desiredStatus is true', function () use ($repository): void { + // GIVEN + $dispatcher = Mockery::mock(DomainEventDispatcher::class); + $usecase = new SetClientStatus($repository, $dispatcher); + + $clientId = new ClientId(Uuid::uuid7()); + $identifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32)); + $name = new ClientName('Test Gateway 2'); + $secret = new ClientSecret('arcadia_sec_' . str_repeat('b', 86)); + + $client = Client::hydrate( + id: $clientId, + name: $name, + identifier: $identifier, + secret: $secret, + isActive: false, + createdAt: new \DateTimeImmutable(), + updatedAt: new \DateTimeImmutable(), + ); + + $repository->add($client); + + $dispatcher->expects('dispatch') + ->once() + ->withArgs(fn ($event): bool => $event instanceof ClientStatusToggled + && $event->clientId->equals($clientId) + && $event->isActive === true); + + $input = new Input($identifier, desiredStatus: true); + + // WHEN + $result = $usecase->execute($input); + + // THEN + expect($result)->toBeInstanceOf(Output::class) + ->and($result->isActive)->toBeTrue(); + + $saved = $repository->find($clientId); + expect($saved?->isActive)->toBeTrue(); + }); });