<?php

namespace AutoAdmin\Bundle\Log\Monolog\Client;

use LogicException;
use Monolog\Handler\Curl\Util;
use function curl_init;
use function curl_setopt;
use function extension_loaded;

class LogtailClient {
    const URL = "https://in.logtail.com";

    private string $sourceToken;
    private string $endpoint;
    /**
     * @var resource $handle
     */
    private $handle = NULL;

    public function __construct($sourceToken, $endpoint = self::URL) {
        if (!extension_loaded('curl')) {
            throw new LogicException('The curl extension is needed to use the LogtailHandler');
        }

        $this->sourceToken = $sourceToken;
        $this->endpoint = $endpoint;
    }

    public function send($data) {
        if (is_null($this->handle)) {
            $this->initCurlHandle();
        }

        curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
        curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, true);

        Util::execute($this->handle, 5, false);
    }

    /**
     * @return void
     */
    private function initCurlHandle() {
        $this->handle = curl_init();

        $headers = [
            'Content-Type: application/json',
            "Authorization: Bearer {$this->sourceToken}"
        ];

        curl_setopt($this->handle, CURLOPT_URL, $this->endpoint);
        curl_setopt($this->handle, CURLOPT_POST, true);
        curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
    }
}
