<?php

declare(strict_types=1);

namespace App\Framework\HttpClient;

use App\Framework\HttpClient\Exception\ResponseValidationException;

final readonly class ResponseValidator
{
    public function validate(ClientResponse $response, ClientOptions $options): void
    {
        if ($options->throwOnError && ! $response->isSuccessful()) {
            $this->throwHttpException($response);
        }

        if (! empty($options->allowedStatusCodes) && ! in_array($response->status->value, $options->allowedStatusCodes)) {
            throw new ResponseValidationException(
                "Status code {$response->status->value} is not in allowed codes: " . implode(', ', $options->allowedStatusCodes)
            );
        }
    }

    private function throwHttpException(ClientResponse $response): void
    {
        $message = "HTTP {$response->status->value}: {$response->status->name}";

        if ($response->isClientError()) {
            throw new \App\Framework\HttpClient\Exception\ClientErrorException($message, $response);
        } elseif ($response->isServerError()) {
            throw new \App\Framework\HttpClient\Exception\ServerErrorException($message, $response);
        }
    }
}
