<?php

declare(strict_types=1);

/*
 * eduVPN - End-user friendly VPN.
 *
 * Copyright: 2016-2023, The Commons Conservancy eduVPN Programme
 * SPDX-License-Identifier: AGPL-3.0+
 */

namespace Vpn\Node\HttpClient;

class HttpClientResponse
{
    private int $statusCode;
    private string $headerList;
    private string $responseBody;

    public function __construct(int $statusCode, string $headerList, string $responseBody)
    {
        $this->statusCode = $statusCode;
        $this->headerList = $headerList;
        $this->responseBody = $responseBody;
    }

    public function __toString(): string
    {
        return $this->statusCode() . PHP_EOL . '---- BODY ----' . PHP_EOL . $this->body() . PHP_EOL . '---- /BODY ----' . PHP_EOL . '---- HEADERS ----' . PHP_EOL . $this->headerList() . PHP_EOL . '---- /HEADERS ----';
    }

    public function statusCode(): int
    {
        return $this->statusCode;
    }

    /**
     * We loop over all available headers and return the value of the first
     * matching header key. If multiple headers with the same name are present
     * the next ones are ignored!
     */
    public function header(string $headerKey): ?string
    {
        foreach (explode("\n", $this->headerList) as $headerLine) {
            $e = explode(':', $headerLine, 2);
            if (2 !== count($e)) {
                continue;
            }
            if (strtolower(trim($headerKey)) === strtolower(trim($e[0]))) {
                return trim($e[1]);
            }
        }

        return null;
    }

    public function headerList(): string
    {
        return $this->headerList;
    }

    public function body(): string
    {
        return $this->responseBody;
    }

    public function isOkay(): bool
    {
        return 200 <= $this->statusCode && 300 > $this->statusCode;
    }
}
