<?php

declare(strict_types=1);

namespace App\Administration\Application\Command\ArchiveSubject;

use App\Administration\Domain\Exception\SubjectNotFoundException;
use App\Administration\Domain\Model\Subject\Subject;
use App\Administration\Domain\Model\Subject\SubjectId;
use App\Administration\Domain\Repository\SubjectRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

/**
 * Handler pour archiver une matière.
 *
 * Note: La vérification des notes associées doit être faite par le Processor API
 * avant d'appeler ce handler (via HasGradesForSubjectQuery).
 */
#[AsMessageHandler(bus: 'command.bus')]
final readonly class ArchiveSubjectHandler
{
    public function __construct(
        private SubjectRepository $subjectRepository,
        private Clock $clock,
    ) {
    }

    public function __invoke(ArchiveSubjectCommand $command): Subject
    {
        $subjectId = SubjectId::fromString($command->subjectId);
        $tenantId = TenantId::fromString($command->tenantId);

        $subject = $this->subjectRepository->get($subjectId);

        // Vérifier que la matière appartient au tenant (défense en profondeur)
        if (!$subject->tenantId->equals($tenantId)) {
            throw SubjectNotFoundException::withId($subjectId);
        }

        $subject->archiver($this->clock->now());

        $this->subjectRepository->save($subject);

        return $subject;
    }
}
