<?php
namespace API\Provigis\Exception;

use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\ResponseInterface;

class ProvigisWsResponseException extends \Exception
{

    private ResponseInterface $_response;

    public function __construct(Request $request, ResponseInterface $response)
    {
        $this->_response = $response;
        parent::__construct(
            'Invalid response '
            .$response->getStatusCode().' : '
            .$response->getBody()
            .' for request '
            . var_export($request, true)
        );
    }

    public function getResponse() :ResponseInterface
    {
        return $this->_response;
    }

    /**
     * @_return ?object{code::string,message:string}
     * @return \stdClass
     */
    public function getError400() :?object
    {
        $response = $this->getResponse();
        if ($response->getStatusCode() != 400) {
            return null;
        }

        $payload = json_decode($response->getBody());
        if ($payload === false || empty($payload->error->code ?? null)) {
            return null;
        }

        return (object) [
            'code' => $payload->error->code,
            'message' => $payload->error->message ?? '',
        ];
    }
}
