<?php
declare(strict_types=1);

namespace App\State\Processor;

use AltchaOrg\Altcha\Altcha;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;
use ApiPlatform\State\ProcessorInterface;
use App\ApiResource\CvPdfRequest;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\Response;
use Path\Path;

class CvPdfRequestProcessor implements ProcessorInterface
{
    public function __construct(
        private readonly string $projectDir,
        private readonly string $hmacKey
    )
    {}

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): Response|RedirectResponse
    {
        if (!$operation instanceof Post) {
            throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
        }

        /** @var CvPdfRequest $cvPdfRequest */
        $cvPdfRequest = $data;

        try {
            $valid = Altcha::verifySolution(
                $cvPdfRequest->getAltchaPayload(),
                $this->hmacKey,
                true
            );
        } catch (\Throwable) {
            $valid = false;
        }

        if (!$valid) {
            throw new \RuntimeException('Invalid payload');
        }

        $content = (new Path($this->projectDir))
            ->append('static', 'CV_Olivier_Massot.pdf')
            ->getContent();

        // Build the response and attach the file to it
        // @see https://symfony.com/doc/current/components/http_foundation.html#serving-files
        $response = new Response($content);

        $response->headers->set('Charset', 'UTF-8');
        $response->headers->set('Access-Control-Expose-Headers', 'Content-Disposition');
        $response->headers->set('Content-Type', 'application/pdf');
        $response->headers->set(
            'Content-Disposition',
            HeaderUtils::makeDisposition(HeaderUtils::DISPOSITION_ATTACHMENT, 'CV_Olivier_Massot.pdf')
        );

        return $response;
    }
}