<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\UploadHomeworkAttachment;

use App\Scolarite\Application\Port\FileStorage;
use App\Scolarite\Domain\Exception\PieceJointeInvalideException;
use App\Scolarite\Domain\Model\Homework\HomeworkAttachment;
use App\Scolarite\Domain\Model\Homework\HomeworkAttachmentId;
use App\Scolarite\Domain\Model\Homework\HomeworkId;
use App\Scolarite\Domain\Repository\HomeworkRepository;
use App\Shared\Domain\Clock;
use App\Shared\Domain\Tenant\TenantId;

use function file_get_contents;
use function sprintf;

use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
final readonly class UploadHomeworkAttachmentHandler
{
    public function __construct(
        private HomeworkRepository $homeworkRepository,
        private FileStorage $fileStorage,
        private Clock $clock,
    ) {
    }

    public function __invoke(UploadHomeworkAttachmentCommand $command): HomeworkAttachment
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $homeworkId = HomeworkId::fromString($command->homeworkId);

        // Valider que le devoir existe
        $this->homeworkRepository->get($homeworkId, $tenantId);

        $attachmentId = HomeworkAttachmentId::generate();
        $storagePath = sprintf('homework/%s/%s/%s/%s', $command->tenantId, $command->homeworkId, (string) $attachmentId, $command->filename);

        $content = file_get_contents($command->tempFilePath);

        if ($content === false) {
            throw PieceJointeInvalideException::lectureFichierImpossible($command->filename);
        }

        $this->fileStorage->upload($storagePath, $content, $command->mimeType);

        return new HomeworkAttachment(
            id: $attachmentId,
            filename: $command->filename,
            filePath: $storagePath,
            fileSize: $command->fileSize,
            mimeType: $command->mimeType,
            uploadedAt: $this->clock->now(),
        );
    }
}
