<?php

declare(strict_types=1);

namespace App\Administration\Application\Query\GetUsers;

use App\Administration\Domain\Model\User\Role;
use App\Administration\Domain\Model\User\StatutCompte;
use App\Administration\Domain\Repository\UserRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'query.bus')]
final readonly class GetUsersHandler
{
    public function __construct(
        private UserRepository $userRepository,
        private Clock $clock,
    ) {
    }

    /**
     * @return UserDto[]
     */
    public function __invoke(GetUsersQuery $query): array
    {
        $users = $this->userRepository->findAllByTenant(
            TenantId::fromString($query->tenantId),
        );

        // Apply filters
        if ($query->role !== null) {
            $filterRole = Role::tryFrom($query->role);
            if ($filterRole !== null) {
                $users = array_filter(
                    $users,
                    static fn ($user) => $user->aLeRole($filterRole),
                );
            }
        }

        if ($query->statut !== null) {
            $filterStatut = StatutCompte::tryFrom($query->statut);
            if ($filterStatut !== null) {
                $users = array_filter(
                    $users,
                    static fn ($user) => $user->statut === $filterStatut,
                );
            }
        }

        return array_values(array_map(
            fn ($user) => UserDto::fromDomain($user, $this->clock),
            $users,
        ));
    }
}
