<?php

declare(strict_types=1);

namespace App\SignDocument\Services;

use App\Infrastructure\External\Api\BinaryStringFileResult;
use App\SignDocument\Api\Api;
use App\SignDocument\Api\ApiParams;
use App\SignDocument\Api\Request\DigitalSignatureRequest;
use App\SignDocument\Api\Response\DigitalSignatureResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Exception;
use RuntimeException;

class DigitalSignatureService
{
    private BinaryStringFileResult $document;

    public function __construct(
        private readonly Api                           $api,
        private readonly ApiParams                     $apiParams,
    ){
    }

    public function __destruct()
    {
        $this->document->remove();
    }

    public function getSignature(DigitalSignatureRequest $request, string $token): DigitalSignatureResponse
    {
        if ($_ENV['API_TOKEN'] !== $request->apiToken) {
            throw new AccessDeniedHttpException('Доступ запрещен');
        }

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

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

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

            $response = base64_encode(file_get_contents($this->document->tempFileName . '.pdf.sgn'));

            return new DigitalSignatureResponse(
                hash: $response,
                content: base64_encode(file_get_contents(sprintf('%s.pdf', $this->document->tempFileName)))
            );
        } catch (Exception $e) {
            throw new RuntimeException($e->getMessage());
        }
    }
}