<?php
declare(strict_types=1);

namespace App\State\Provider;

use AltchaOrg\Altcha\Altcha;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\ApiResource\CvPdfRequest;
use App\ApiResource\IdCardRequest;
use Path\Exception\FileNotFoundException;
use Path\Exception\IOException;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Path\Path;

class IdCardRequestProvider implements ProviderInterface
{
    public function __construct(
        private readonly string $projectDir,
        private readonly string $hmacKey,
        private readonly string $idAge,
        private readonly string $idPlace,
        private readonly string $idStatus,
    )
    {}

    /**
     * @throws IOException
     * @throws FileNotFoundException
     */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): IdCardRequest
    {
        if (!$operation instanceof Get) {
            throw new \RuntimeException('not supported', Response::HTTP_METHOD_NOT_ALLOWED);
        }

        $filters = $context['filters'] ?? [];
        $altchaPayload = $filters['payload'] ?? null;
        if ($altchaPayload === null) {
            throw new \RuntimeException('missing parameter: payload', Response::HTTP_BAD_REQUEST);
        }

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

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

        $photo = (new Path($this->projectDir))
            ->append('static', 'profile.min.png')
            ->getContent();

        $idCardRequest = new IdCardRequest();
        $idCardRequest->setPhoto(base64_encode($photo));
        $idCardRequest->setPlace($this->idPlace);
        $idCardRequest->setAge($this->idAge);
        $idCardRequest->setStatus($this->idStatus);

        return $idCardRequest;
    }
}