<?php

namespace App\Controller\Api;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Cache\CacheInterface;

class ExtensionController extends AbstractApiController
{
    #[Route('/content', methods: ['POST'])]
    public function setContent(
        Request $request,
        CacheInterface $cache,
    ): Response {
        // Parse JSON payload
        $data = json_decode($request->getContent(), true);
        if (!$data || !isset($data['html'])) {
            return $this->errorResponse('Invalid JSON payload: Missing html parameter');
        }
        $html = $data['html'];

        // Store HTML in cache with unique key
        $userId = $this->getUser()?->getId();
        $cacheKey = 'html_' . $userId . '_' . bin2hex(random_bytes(8));
        $cache->get($cacheKey, function () use ($html) {
            // value to cache
            return $html;
        });

        // Build URL to redirect user to a form page later
        $formUrl = $this->generateUrl(
            'snip_new',
            ['cacheKey' => $cacheKey],
            UrlGeneratorInterface::ABSOLUTE_URL
        );

        return $this->successResponse(['url' => $formUrl]);
    }
}
