<?php

declare(strict_types=1);

namespace NoahVet\Reef\Test\A_Unit\Factory;

use NoahVet\Reef\Factory\ClientFactory;
use NoahVet\Reef\Jane\Client;
use NoahVet\Reef\Plugin\Cache\HttpResponseCacheInterface;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;

class ClientFactoryTest extends TestCase
{
    public function testCreateSuccessful(): void
    {
        $reefUrl = 'https://example.com';
        $bearerToken = 'dummyToken';
        $httpResponseCache = $this->createMock(HttpResponseCacheInterface::class);
        $clientFactory = new ClientFactory($reefUrl, $httpResponseCache);

        $client = $clientFactory->create($bearerToken);

        $this->assertInstanceOf(Client::class, $client);
    }

    public function testCreateWithCachePlugin(): void
    {
        $reefUrl = 'https://example.com';
        $bearerToken = 'dummyToken';
        $httpResponseCache = $this->createMock(HttpResponseCacheInterface::class);
        $clientFactory = new ClientFactory($reefUrl, $httpResponseCache);
        $response = $this->createMock(ResponseInterface::class);
        $response->method('getStatusCode')->willReturn(200);
        $responseBody = $this->createMock(StreamInterface::class);

        $client = $clientFactory->create($bearerToken);

        $this->assertInstanceOf(Client::class, $client);

        $httpResponseCache
            ->expects($this->once())
            ->method('getCachedResponse')
            ->willReturn($response)
        ;

        $response
            ->method('hasHeader')
            ->with('Content-Type')
            ->willReturn(true)
        ;

        $response
            ->method('getHeader')
            ->with('Content-Type')
            ->willReturn(['application/json'])
        ;

        $response
            ->method('getBody')
            ->willReturn($responseBody)
        ;

        $responseBody->method('__toString')->willReturn('{"sub":"b0199a11-47aa-4553-975e-4228ebc9fb22"}');

        $userinfo = $client->userinfo();

        $this->assertEquals('b0199a11-47aa-4553-975e-4228ebc9fb22', $userinfo->getSub());
    }
}
