<?php

namespace MintyPHP\Tests\Module\Helpdesk\Service;

use MintyPHP\Module\Helpdesk\Repository\HelpdeskTokenRepository;
use MintyPHP\Service\Settings\SettingsCryptoGatewayInterface;
use PHPUnit\Framework\TestCase;

/**
 * Tests for HelpdeskTokenRepository edge-case validation paths.
 *
 * Note: DB-dependent paths (findValidToken with actual DB, storeToken INSERT)
 * require integration tests against a real database. These unit tests cover
 * the input validation and error handling that runs before DB access.
 */
class HelpdeskTokenRepositoryTest extends TestCase
{
    private function createRepository(?SettingsCryptoGatewayInterface $crypto = null): HelpdeskTokenRepository
    {
        $crypto = $crypto ?? $this->createMock(SettingsCryptoGatewayInterface::class);

        return new HelpdeskTokenRepository($crypto);
    }

    public function testFindValidTokenReturnsNullForZeroTenantId(): void
    {
        $repo = $this->createRepository();
        $this->assertNull($repo->findValidToken(0));
    }

    public function testFindValidTokenReturnsNullForNegativeTenantId(): void
    {
        $repo = $this->createRepository();
        $this->assertNull($repo->findValidToken(-1));
    }

    public function testStoreTokenReturnsFalseForZeroTenantId(): void
    {
        $repo = $this->createRepository();
        $this->assertFalse($repo->storeToken(0, 'token', new \DateTimeImmutable('+1 hour')));
    }

    public function testStoreTokenReturnsFalseForNegativeTenantId(): void
    {
        $repo = $this->createRepository();
        $this->assertFalse($repo->storeToken(-5, 'token', new \DateTimeImmutable('+1 hour')));
    }

    public function testStoreTokenReturnsFalseForEmptyAccessToken(): void
    {
        $repo = $this->createRepository();
        $this->assertFalse($repo->storeToken(1, '', new \DateTimeImmutable('+1 hour')));
    }

    public function testStoreTokenReturnsFalseWhenEncryptionFails(): void
    {
        $crypto = $this->createMock(SettingsCryptoGatewayInterface::class);
        $crypto->method('encryptString')->willThrowException(new \RuntimeException('encryption failed'));

        $repo = $this->createRepository($crypto);
        $this->assertFalse($repo->storeToken(1, 'valid-token', new \DateTimeImmutable('+1 hour')));
    }
}
