<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Storage;

use App\Administration\Application\Port\LogoStorage;

use function dirname;

use Override;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Stockage local des logos sur le système de fichiers.
 *
 * TODO: Remplacer par un S3LogoStorage en production.
 */
final readonly class LocalLogoStorage implements LogoStorage
{
    public function __construct(
        private string $uploadDir,
        private string $publicPath,
        private RequestStack $requestStack,
    ) {
    }

    #[Override]
    public function store(string $content, string $key, string $contentType): string
    {
        $path = $this->uploadDir . '/' . $key;

        $dir = dirname($path);
        if (!is_dir($dir)) {
            mkdir($dir, 0o755, true);
        }

        file_put_contents($path, $content);

        return $this->buildAbsoluteUrl($key);
    }

    #[Override]
    public function delete(string $key): void
    {
        $path = $this->uploadDir . '/' . $key;

        if (file_exists($path)) {
            unlink($path);
        }
    }

    private function buildAbsoluteUrl(string $key): string
    {
        $request = $this->requestStack->getCurrentRequest();

        if ($request !== null) {
            return $request->getSchemeAndHttpHost() . $this->publicPath . '/' . $key;
        }

        return 'http://localhost' . $this->publicPath . '/' . $key;
    }
}
