<?php

namespace Chatbeep\Sdk;

use RuntimeException;

class ChatbeepClient
{
    public function __construct(
        private readonly string $baseUrl,
        private readonly ?string $bearerToken = null,
    ) {}

    public function widgetConfig(string $installationToken): array
    {
        return $this->request('GET', '/api/widget/config/'.$installationToken);
    }

    public function installationHealth(string $installationToken, ?string $currentUrl = null): array
    {
        $path = '/api/widget/installations/'.$installationToken.'/health';

        if ($currentUrl) {
            $path .= '?current_url='.rawurlencode($currentUrl);
        }

        return $this->request('GET', $path);
    }

    public function createConversation(array $payload): array
    {
        return $this->request('POST', '/api/widget/conversations', $payload);
    }

    public function mobileLogin(string $email, string $password, string $deviceName): array
    {
        return $this->request('POST', '/api/mobile/login', [
            'email' => $email,
            'password' => $password,
            'device_name' => $deviceName,
        ]);
    }

    public function mobileMe(): array
    {
        return $this->request('GET', '/api/mobile/me', [], true);
    }

    public function mobileConversations(array $query = []): array
    {
        $path = '/api/mobile/conversations';

        if ($query !== []) {
            $path .= '?'.http_build_query($query);
        }

        return $this->request('GET', $path, [], true);
    }

    private function request(string $method, string $path, array $payload = [], bool $requiresAuth = false): array
    {
        $headers = [
            'Accept: application/json',
        ];

        if ($requiresAuth) {
            if (! $this->bearerToken) {
                throw new RuntimeException('Bearer token is required for this call.');
            }

            $headers[] = 'Authorization: Bearer '.$this->bearerToken;
        }

        $content = null;

        if ($payload !== []) {
            $headers[] = 'Content-Type: application/json';
            $content = json_encode($payload, JSON_THROW_ON_ERROR);
        }

        $context = stream_context_create([
            'http' => [
                'method' => $method,
                'header' => implode("\r\n", $headers),
                'content' => $content,
                'ignore_errors' => true,
            ],
        ]);

        $response = file_get_contents(rtrim($this->baseUrl, '/').$path, false, $context);

        if ($response === false) {
            throw new RuntimeException('Chatbeep request failed.');
        }

        return json_decode($response, true, 512, JSON_THROW_ON_ERROR);
    }
}
