<?php

namespace App\Modules\Media\Application\Create;

use App\Modules\Media\Domain\FileReceptor;
use App\Modules\Media\Domain\ImageThumbnailCreator;
use App\Modules\Media\Domain\Media;
use App\Modules\Media\Domain\MediaData;
use App\Modules\Media\Domain\MediaNotAvailable;
use App\Modules\Media\Domain\MediaRepository;
use App\Modules\Media\Domain\MediaSaveConfiguration;
use App\Modules\Media\Domain\MediaType;
use App\Modules\Media\Domain\VideoThumbnailCreator;

final class MediaCreator
{
    public const THUMBNAIL_WIDTH = 200;
    public const THUMBNAIL_HEIGHT = 200;
    public const LARGE_THUMBNAIL_WIDTH = 1032;
    public const LARGE_THUMBNAIL_HEIGHT = 905;

    public function __construct(
        private MediaRepository $repository,
        private FileReceptor $fileReceptor,
        private ImageThumbnailCreator $imageThumbnailCreator,
        private VideoThumbnailCreator $videoThumbnailCreator
    ) {}

    public function __invoke(Media $creator, $directoryName = null): MediaData
    {
        $config = new MediaSaveConfiguration(
            self::THUMBNAIL_WIDTH,
            self::THUMBNAIL_HEIGHT,
            self::LARGE_THUMBNAIL_WIDTH,
            self::LARGE_THUMBNAIL_HEIGHT,
            true
        );
        $type = $this->fileReceptor->getType($creator->inputName()->value());
        if ($type->value() === MediaType::IMAGE) {
            return $this->repository->save(
                $creator,
                $config,
                $this->imageThumbnailCreator,
                MediaType::image(),
                $directoryName
            );
        } else if ($type->value() === MediaType::VIDEO) {
            return $this->repository->save(
                $creator,
                $config,
                $this->videoThumbnailCreator,
                MediaType::video(),
                $directoryName
            );
        } else {
            throw new MediaNotAvailable('File not available');
        }
    }
}
