<?php

namespace Chatbeep\Laravel;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

class ChatbeepManager
{
    public function __construct(
        private readonly string $baseUrl,
        private readonly ?string $token,
        private readonly int $timeout,
    ) {}

    public function withToken(?string $token = null): self
    {
        return new self($this->baseUrl, $token ?? $this->token, $this->timeout);
    }

    public function widgetConfig(string $installationToken): array
    {
        return $this->client()->get('/api/widget/config/'.$installationToken)->json();
    }

    public function installationHealth(string $installationToken, ?string $currentUrl = null): array
    {
        return $this->client()->get('/api/widget/installations/'.$installationToken.'/health', [
            'current_url' => $currentUrl,
        ])->json();
    }

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

    public function mobileMe(): array
    {
        return $this->client(true)->get('/api/mobile/me')->json();
    }

    public function mobileConversations(array $query = []): array
    {
        return $this->client(true)->get('/api/mobile/conversations', $query)->json();
    }

    private function client(bool $requiresAuth = false): PendingRequest
    {
        $request = Http::baseUrl(rtrim($this->baseUrl, '/'))
            ->acceptJson()
            ->timeout($this->timeout);

        if ($requiresAuth && $this->token) {
            $request = $request->withToken($this->token);
        }

        return $request;
    }
}
