<?php

declare(strict_types=1);

namespace App\SignDocument\Services;

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

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

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

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

            $this->sign($document->tempFileName);

            $response = $this->api->send($token, $document->tempFileName . '_sign.pdf', $request->batch);

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

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

    private function sign (string $documentUrl): void
    {
        match ($_ENV['APP_ENV']) {
            'dev' => $this->devSignService->sign($documentUrl),
            'prod' => $this->prodSignService->sign($documentUrl),
        };
    }
}