<?php

namespace Fifa\ConnectServiceBus\Sdk\ExceptionHandler\Handler;

use Fifa\ConnectServiceBus\Sdk\Api\ApiException;
use Fifa\ConnectServiceBus\Sdk\Api\Model\TooManyRequestsResponseType;
use Fifa\ConnectServiceBus\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;
    }
}