<?php

declare(strict_types=1);

namespace App;

use App\Api\Api;
use App\Api\ApiParams;
use App\Api\Request\SignRequest;
use App\Infrastructure\External\Api\BinaryStringFileResult;
use Exception;
use RuntimeException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class SignService
{
    private DevSignService $devSignService;
    private ProdSignService $prodSignService;

    public function __construct(
        private Api $api,
        private ApiParams $apiParams
    ){
        $this->devSignService = new DevSignService();
        $this->prodSignService = new ProdSignService();
    }
    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->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),
        };
    }

    private function removeExistingDocument(BinaryStringFileResult $document): void
    {
        if (file_exists($document->tempFileName)) {
            unlink($document->tempFileName);
        }
    }
}