<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\MessageHandler;

use Contao\CoreBundle\Filesystem\VirtualFilesystemInterface;
use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Message\GenerateImage;
use Ferienpass\CoreBundle\Service\OpenAiClient;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;

#[AsMessageHandler(bus: 'command.bus')]
class GenerateImageHandler
{
    public function __construct(
        private readonly OpenAiClient $openAiClient,
        #[Autowire(service: 'contao.filesystem.virtual.media')]
        private readonly VirtualFilesystemInterface $filesystem,
        private readonly EntityManagerInterface $entityManager,
        private readonly CacheInterface $cache,
    ) {
    }

    public function __invoke(GenerateImage $message): void
    {
        $imageDataBase64 = $this->openAiClient->generateImage($message->getPrompt());

        $this->cache->delete('ai_image_'.$message->getJobId());
        $this->cache->get('ai_image_'.$message->getJobId(), static function (ItemInterface $item) use ($imageDataBase64) {
            $item->expiresAfter(3600);

            return [
                'base64' => $imageDataBase64,
            ];
        });
    }
}
