<?php

namespace MintyPHP\Tests\Module\Helpdesk\Service;

use MintyPHP\Module\Helpdesk\Service\EffectiveHelpdeskSettingsService;
use MintyPHP\Module\Helpdesk\Service\HelpdeskOAuthTokenService;
use MintyPHP\Module\Helpdesk\Service\HelpdeskSettingsGateway;
use MintyPHP\Module\Helpdesk\Repository\HelpdeskTokenRepository;
use PHPUnit\Framework\TestCase;

class HelpdeskOAuthTokenServiceTest extends TestCase
{
    private function createService(?string $authMode = null, ?string $cachedToken = null): HelpdeskOAuthTokenService
    {
        $settings = $this->createMock(EffectiveHelpdeskSettingsService::class);
        $settings->method('getAuthMode')->willReturn($authMode ?? HelpdeskSettingsGateway::AUTH_MODE_BASIC);

        $tokenRepo = $this->createMock(HelpdeskTokenRepository::class);
        $tokenRepo->method('findValidToken')->willReturn($cachedToken);

        return new HelpdeskOAuthTokenService($settings, $tokenRepo);
    }

    public function testReturnsNullWhenAuthModeIsBasic(): void
    {
        $service = $this->createService(HelpdeskSettingsGateway::AUTH_MODE_BASIC);
        $this->assertNull($service->getAccessToken(1));
    }

    public function testReturnsCachedTokenWhenAvailable(): void
    {
        $service = $this->createService(HelpdeskSettingsGateway::AUTH_MODE_OAUTH2, 'cached-bearer-token');
        $this->assertSame('cached-bearer-token', $service->getAccessToken(1));
    }

    public function testReturnsNullWhenNoCachedTokenExists(): void
    {
        $service = $this->createService(HelpdeskSettingsGateway::AUTH_MODE_OAUTH2, null);
        $this->assertNull($service->getAccessToken(1));
    }

    public function testReturnsNullForBasicAuthRegardlessOfTenantId(): void
    {
        $service = $this->createService(HelpdeskSettingsGateway::AUTH_MODE_BASIC);
        $this->assertNull($service->getAccessToken(99));
    }

    public function testDoesNotQueryCacheWhenAuthModeIsBasic(): void
    {
        $settings = $this->createMock(EffectiveHelpdeskSettingsService::class);
        $settings->method('getAuthMode')->willReturn(HelpdeskSettingsGateway::AUTH_MODE_BASIC);

        $tokenRepo = $this->createMock(HelpdeskTokenRepository::class);
        $tokenRepo->expects($this->never())->method('findValidToken');

        $service = new HelpdeskOAuthTokenService($settings, $tokenRepo);
        $service->getAccessToken(1);
    }

    public function testDoesNotQueryCacheForInvalidTenantId(): void
    {
        $settings = $this->createMock(EffectiveHelpdeskSettingsService::class);
        $settings->method('getAuthMode')->willReturn(HelpdeskSettingsGateway::AUTH_MODE_OAUTH2);

        $tokenRepo = $this->createMock(HelpdeskTokenRepository::class);
        $tokenRepo->expects($this->never())->method('findValidToken');

        $service = new HelpdeskOAuthTokenService($settings, $tokenRepo);
        $this->assertNull($service->getAccessToken(0));
    }
}
