<?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,
        protected readonly string $publicLegacyBaseUrl,
    ) {
    }

    public function exists(File $file): bool
    {
        throw new \RuntimeException('not implemented error');
    }

    /**
     * Reads the given file and returns its content as a 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.
     */
    public function getImageUrl(File $file, string $size, bool $relativePath, bool $uncropped = false): string
    {
        $url = sprintf('api/files/%s/download/%s?relativePath=1', $file->getId(), $size);

        if ($uncropped) {
            $url .= '&noCache=true';
        }

        // L'url interne est l'équivalent d'un chemin relatif dans ce cas
        $baseUrl = $relativePath ? $this->legacyBaseUrl : $this->publicLegacyBaseUrl;

        return UrlBuilder::concat($baseUrl, [$this->apiLegacyRequestService->getContent($url)], []);
    }

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

    /**
     * Permanently delete the entire file storage of the given Organization.
     */
    public function deleteOrganizationFiles(int $organizationId): void
    {
        $url = sprintf('/_internal/request/organization-files/delete/%s', $organizationId);
        $this->apiLegacyRequestService->get($url);
    }

    /**
     * Permanently delete the entire file storage of the given Person.
     */
    public function deletePersonFiles(int $personId): void
    {
        $url = sprintf('/_internal/request/person-files/delete/%s', $personId);
        $this->apiLegacyRequestService->get($url);
    }
}
