<?php

declare(strict_types=1);

namespace App\Scolarite\Application\Command\UploadSubmissionAttachment;

use App\Scolarite\Application\Port\FileStorage;
use App\Scolarite\Domain\Exception\PieceJointeInvalideException;
use App\Scolarite\Domain\Exception\RenduDejaSoumisException;
use App\Scolarite\Domain\Model\HomeworkSubmission\HomeworkSubmissionId;
use App\Scolarite\Domain\Model\HomeworkSubmission\SubmissionAttachment;
use App\Scolarite\Domain\Model\HomeworkSubmission\SubmissionAttachmentId;
use App\Scolarite\Domain\Repository\HomeworkSubmissionRepository;
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 UploadSubmissionAttachmentHandler
{
    public function __construct(
        private HomeworkSubmissionRepository $submissionRepository,
        private FileStorage $fileStorage,
        private Clock $clock,
    ) {
    }

    public function __invoke(UploadSubmissionAttachmentCommand $command): SubmissionAttachment
    {
        $tenantId = TenantId::fromString($command->tenantId);
        $submissionId = HomeworkSubmissionId::fromString($command->submissionId);

        $submission = $this->submissionRepository->get($submissionId, $tenantId);

        if (!$submission->status->estModifiable()) {
            throw RenduDejaSoumisException::pourRendu($submissionId);
        }

        $attachmentId = SubmissionAttachmentId::generate();
        $storagePath = sprintf(
            'submissions/%s/%s/%s/%s',
            $command->tenantId,
            $command->submissionId,
            (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 SubmissionAttachment(
            id: $attachmentId,
            filename: $command->filename,
            filePath: $storagePath,
            fileSize: $command->fileSize,
            mimeType: $command->mimeType,
            uploadedAt: $this->clock->now(),
        );
    }
}
