<?php

namespace App\Domain\Conversion\Application\CommandHandler;

use App\Domain\Conversion\Application\Command\ConvertFileCommand;
use App\Domain\Conversion\Application\Response\ConversionResponse;
use App\Domain\Conversion\Domain\Contract\ConversionServiceInterface;
use App\Domain\Conversion\Domain\Exception\ConversionException;
use App\Domain\Conversion\Domain\Model\ConversionRequest;

final readonly class ConvertFileCommandHandler
{
    private const MAX_FILE_SIZE = 150 * 1024 * 1024; // 150MB

    public function __construct(
        private ConversionServiceInterface $conversionService
    ) {
    }

    public function handle(ConvertFileCommand $command): ConversionResponse
    {
        $this->validateCommand($command);

        $request = new ConversionRequest(
            filePath: $command->filePath,
            originalFilename: $command->originalFilename,
            fileSize: $command->fileSize
        );

        $result = $this->conversionService->convert($request);

        return ConversionResponse::fromConversionResult($result);
    }

    private function validateCommand(ConvertFileCommand $command): void
    {
        if (!file_exists($command->filePath)) {
            throw ConversionException::fileNotFound($command->filePath);
        }

        if ($command->fileSize > self::MAX_FILE_SIZE) {
            throw ConversionException::fileSizeExceedsLimit($command->fileSize, self::MAX_FILE_SIZE);
        }

        $extension = strtolower(pathinfo($command->originalFilename, PATHINFO_EXTENSION));
        $allowedExtensions = ['cbr', 'cbz', 'zip', 'rar'];

        if (!in_array($extension, $allowedExtensions)) {
            throw ConversionException::invalidFileFormat($command->originalFilename);
        }
    }
}
