<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Glide;

use League\Flysystem\FilesystemOperator;
use League\Glide\Responses\ResponseFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

final class SymfonyResponseFactory implements ResponseFactoryInterface
{
    public function __construct(
        private readonly ?Request $request = null,
    ) {
    }

    public function create(FilesystemOperator $cache, $path): StreamedResponse
    {
        $stream = $cache->readStream($path);
        if (false === $stream) {
            throw new \RuntimeException(\sprintf('Unable to open cached image "%s".', $path));
        }

        $response = new StreamedResponse();
        $response->headers->set('Content-Type', $cache->mimeType($path));
        $response->headers->set('Content-Length', (string) $cache->fileSize($path));
        $response->setPublic();
        $response->setMaxAge(31536000);
        $response->setExpires(date_create()->modify('+1 years'));

        if (null !== $this->request) {
            $response->setLastModified(date_create()->setTimestamp($cache->lastModified($path)));
            $response->isNotModified($this->request);
        }

        $response->setCallback(static function () use ($stream): void {
            try {
                if (0 !== ftell($stream)) {
                    rewind($stream);
                }

                fpassthru($stream);
            } finally {
                fclose($stream);
            }
        });

        return $response;
    }
}
