<?php

declare(strict_types=1);

namespace App\Administration\Application\Command\UpdateImageRights;

use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Domain\Model\User\ImageRightsStatus;
use App\Administration\Domain\Model\User\Role;
use App\Administration\Domain\Model\User\User;
use App\Administration\Domain\Model\User\UserId;
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: 'command.bus')]
final readonly class UpdateImageRightsHandler
{
    public function __construct(
        private UserRepository $userRepository,
        private Clock $clock,
    ) {
    }

    public function __invoke(UpdateImageRightsCommand $command): User
    {
        $studentId = UserId::fromString($command->studentId);
        $user = $this->userRepository->get($studentId);

        if (!$user->tenantId->equals(TenantId::fromString($command->tenantId))) {
            throw UserNotFoundException::withId($studentId);
        }

        if (!$user->aLeRole(Role::ELEVE)) {
            throw UserNotFoundException::withId($studentId);
        }

        $modifierId = UserId::fromString($command->modifiedBy);
        $status = ImageRightsStatus::from($command->status);

        $user->modifierDroitImage($status, $modifierId, $this->clock->now());

        $this->userRepository->save($user);

        return $user;
    }
}
