<?php

namespace Fifa\ConnectId\Sdk\ExceptionHandler\Handler;

use Fifa\ConnectId\Sdk\Api\ApiException;
use Fifa\ConnectId\Sdk\Api\Model\TooManyRequestsResponseType;
use Fifa\ConnectId\Sdk\Exception\TooManyRequestsException;

class TooManyRequestsHandler implements HandlerInterface
{
    /**
     * @var string
     */
    const RETRY_AFTER_HEADER_NAME = 'Retry-After';

    /**
     * Handler method for TooManyRequestsException
     *
     * @param ApiException $e
     * @return TooManyRequestsException|null
     */
    public function handle(ApiException $e): ?TooManyRequestsException
    {
        $response = $e->getResponseObject();
        $responseHeaders = $e->getResponseHeaders();
        $retryAfterHeaderValue = $responseHeaders[self::RETRY_AFTER_HEADER_NAME] ?? null;
        $retryAfter = $retryAfterHeaderValue != null ? intval($retryAfterHeaderValue) : -1;

        if ($response instanceof TooManyRequestsResponseType && $response->getStatusCode() == 429 && $retryAfter > 0) {
            return new TooManyRequestsException($e, $response, $retryAfter);
        }

        return null;
    }
}