<?php
declare(strict_types=1);

namespace App\Service\File\Storage;

use App\Entity\Core\File;
use App\Enum\Core\FileHostEnum;
use App\Service\ApiLegacy\ApiLegacyRequestService;
use App\Service\Utils\UrlBuilder;
use Liip\ImagineBundle\Imagine\Data\DataManager;

/**
 * Read and write files into the Opentalent API v1 storage
 */
class ApiLegacyStorage implements FileStorageInterface
{
    public function __construct(
        private readonly ApiLegacyRequestService $apiLegacyRequestService,
        protected readonly DataManager $dataManager,
        protected readonly UrlBuilder $urlBuilder,
        protected readonly string $legacyBaseUrl
    )
    {}

    /**
     * Reads the given file and returns its content as a string
     *
     * @param File $file
     * @return string
     */
    public function read(File $file): string
    {
        $url = sprintf('_internal/secure/files/%s', $file->getId());
        return $this->apiLegacyRequestService->getContent($url);
    }

    /**
     * Retoune l'URL de l'image, à la bonne taille, contenu dans la File
     * @param File $file
     * @param string $size
     * @param bool $relativePath
     * @return string
     */
    public function getImageUrl(File $file, string $size, bool $relativePath): string{
        $url = sprintf('api/files/%s/download/%s?relativePath=1', $file->getId(), $size);
        return UrlBuilder::concat($this->legacyBaseUrl, [$this->apiLegacyRequestService->getContent($url)], []);
    }

    /**
     * @param File $file
     * @return bool
     */
    public function support(File $file): bool
    {
        return $file->getHost() === FileHostEnum::API1()->getValue();
    }
}
