<?php

declare(strict_types=1);

namespace App\SignDocument\Services;

use App\SignDocument\Api\Api;
use App\SignDocument\Api\ApiParams;
use App\SignDocument\Api\Request\DigitalSignatureRequest;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Exception;
use RuntimeException;

class DigitalSignatureService
{
    public function __construct(
        private readonly Api                           $api,
        private readonly ApiParams                     $apiParams,
        private readonly RemoveExistingDocumentService $removeExistingDocumentService,
    ){
    }
    public function getSignature(DigitalSignatureRequest $request, string $token): string
    {
        if ($_ENV['API_TOKEN'] !== $request->apiToken) {
            throw new AccessDeniedHttpException('Доступ запрещен');
        }

        $this->api->apiParams = $this->apiParams;

        try {
            $document = $this->api->download($request->url, $token);

            exec(sprintf('cp %s %s.pdf', $document->tempFileName, $document->tempFileName));
            $signature = exec(sprintf('cryptcp -sign -detached -der %s', $document->tempFileName));

            $response = base64_encode($signature);

            $this->removeExistingDocumentService->removeExistingDocument($document);

            return $response;
        } catch (Exception $e) {
            throw new RuntimeException($e->getMessage());
        }
    }
}