<?php

namespace App\Platform\Tools;

use App\Utils\Log;
use GuzzleHttp\RetryMiddleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;


class GuzzleRetryConfig
{

    const MAX_RETRIES = 3;

    public static function retryPolicy() : callable
    {
        return  function (int $retries, RequestInterface $request, ResponseInterface $response, ?\Throwable $exception):bool
        {
            return
                // @TODO  add host check when response is redirect may cause error
                $retries < self::MAX_RETRIES
                && in_array($response->getStatusCode(), [429, 500]);
        };
    }


    public static function retryDelay() : callable
    {

        return function (int $retries, ResponseInterface $response): int
        {
            $delay = 0;

            if (!$response->hasHeader('Retry-After')) {
                $delay = RetryMiddleware::exponentialDelay($retries);
            } else {
                $retryAfter = $response->getHeaderLine('Retry-After');
                $delay = $retryAfter;

                if (!is_numeric($retryAfter)) {
                    $delay = (new \DateTime($retryAfter))->getTimestamp() - time();
                }
                $delay = (int)$delay * 1000;
            }

            $code = $response->getStatusCode();
            $seconds = $delay / 1000;
            $message = "请求失败, 远程服务器响应码为 $code, 此为第 $retries 次尝试，{$seconds} 秒之后重试";

            dump($message);
            Log::warning($message);

            return $delay;
        };

    }


}
