<?php

declare(strict_types=1);

namespace App\Administration\Application\Command\DeleteLogo;

use App\Administration\Application\Service\LogoUploader;
use App\Administration\Domain\Model\SchoolBranding\SchoolBranding;
use App\Administration\Domain\Model\SchoolClass\SchoolId;
use App\Administration\Domain\Repository\SchoolBrandingRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
final readonly class DeleteLogoHandler
{
    public function __construct(
        private SchoolBrandingRepository $brandingRepository,
        private LogoUploader $logoUploader,
        private Clock $clock,
    ) {
    }

    public function __invoke(DeleteLogoCommand $command): SchoolBranding
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $schoolId = SchoolId::fromString($command->schoolId);

        $branding = $this->brandingRepository->get($schoolId, $tenantId);

        if ($branding->logoUrl !== null) {
            $this->logoUploader->deleteByUrl($branding->logoUrl);
        }

        $branding->supprimerLogo($this->clock->now());

        $this->brandingRepository->save($branding);

        return $branding;
    }
}
