<?php

declare(strict_types=1);

namespace App\Administration\Application\Query\CheckImageRights;

use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Domain\Model\User\ImageRightsStatus;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\UserRepository;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

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

    public function __invoke(CheckImageRightsQuery $query): ImageRightsCheckResult
    {
        $studentId = UserId::fromString($query->studentId);
        $user = $this->userRepository->get($studentId);

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

        $status = $user->imageRightsStatus;

        return new ImageRightsCheckResult(
            status: $status,
            canPublish: $status->estAutorise(),
            warningMessage: match ($status) {
                ImageRightsStatus::REFUSED => "ATTENTION : Cet élève n'a PAS l'autorisation de droit à l'image. Publication interdite.",
                ImageRightsStatus::NOT_SPECIFIED => "Attention : Le statut droit à l'image n'est pas renseigné pour cet élève.",
                ImageRightsStatus::AUTHORIZED => null,
            },
        );
    }
}
