<?php

namespace AutoAdmin\Bundle\Media\Library;

use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use AutoAdmin\Bundle\Media\Model\Library\BaseMediaInterface;

class MediaPathGenerator
{
    public function __construct(
        protected MediaTypeResolver $typeResolver,
        protected SiteContextHelper $contextHelper,
    ) {
    }

    public function generateWebPath(BaseMediaInterface $media)
    {
        $typeSlug = $this->typeResolver->getTypeSlug(get_class($media));
        $config = $this->typeResolver->getTypeConfig($typeSlug);
        $url = $this->replaceKnownTags($media, $config['public_path']);

        return $url;
    }

    public function generatePath(BaseMediaInterface $media, ?string $alternativeFilename = null)
    {
        $typeSlug = $this->typeResolver->getTypeSlug(get_class($media));
        $config = $this->typeResolver->getTypeConfig($typeSlug);
        $url = $this->replaceKnownTags($media, $config['path']);

        return $url;
    }

    protected function replaceKnownTags(BaseMediaInterface $media, string $pattern, ?string $alternativeFilename = null): string
    {
        $typeSlug = $this->typeResolver->getTypeSlug(get_class($media));

        $replace = [
            '{site_slug}' => $this->contextHelper->getSite()->getSlug(),
            '{type_slug}' => $typeSlug,
            '{filename}' => $alternativeFilename?: $media->getCurrentTranslation()->getFilename(),
        ];

        $path = str_replace(array_keys($replace), array_values($replace), $pattern);

        return $path;
    }
}