<?php

declare(strict_types=1);

namespace Hexspoor\MonitorClient;

use Hexspoor\Interoperability\Http\Header;
use Hexspoor\MonitorClient\Contracts\ClientContract;
use Hexspoor\MonitorClient\Models\MonitorLog;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use function json_encode;
use function trim;

final class Client implements ClientContract
{
    private string $url;

    private string $token;

    private int $systemId;

    public function __construct(string $url, string $token, int $systemId)
    {
        $this->url = $url;
        $this->token = $token;
        $this->systemId = $systemId;
    }

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

    public function postLogs(array $logs): Response
    {
        return $this->post('log', json_encode(['logs' => $logs]));
    }

    public function post(string $endpoint, string $content): Response
    {
        $request = Http::withToken($this->token);

        return $request
            ->withHeaders([
                Header::X_SYSTEM_ID => $this->systemId,
            ])
            ->withBody($content, 'application/json')
            ->post($this->formatUrl('microservice/' . $endpoint));
    }

    private function formatUrl(string $url): string
    {
        $baseUrl = trim($this->url, '/');

        return "{$baseUrl}/{$url}";
    }
}
