<?php

namespace MintyPHP\Tests\Service\Settings;

use MintyPHP\Repository\Settings\SettingRepositoryInterface;
use MintyPHP\Service\Settings\SettingsCryptoGatewayInterface;
use MintyPHP\Service\Settings\SettingsMetadataGateway;
use MintyPHP\Service\Settings\SettingsMicrosoftGateway;
use PHPUnit\Framework\TestCase;

class SettingsMicrosoftGatewayTest extends TestCase
{
    public function testSetMicrosoftAuthorityRequiresHttps(): void
    {
        $settings = $this->createMock(SettingRepositoryInterface::class);
        $settings->expects($this->never())->method('set');

        $crypto = $this->createMock(SettingsCryptoGatewayInterface::class);
        $gateway = new SettingsMicrosoftGateway(new SettingsMetadataGateway($settings), $crypto);

        $this->assertFalse($gateway->setMicrosoftAuthority('http://login.microsoftonline.com/common/v2.0'));
    }

    public function testGetMicrosoftSharedClientSecretReturnsNullWhenDecryptFails(): void
    {
        $settings = $this->createMock(SettingRepositoryInterface::class);
        $settings->method('getValue')->willReturn('encrypted');

        $crypto = $this->createMock(SettingsCryptoGatewayInterface::class);
        $crypto->method('decryptString')->willThrowException(new \RuntimeException('bad secret'));

        $gateway = new SettingsMicrosoftGateway(new SettingsMetadataGateway($settings), $crypto);
        $this->assertNull($gateway->getMicrosoftSharedClientSecret());
    }

    public function testSetMicrosoftSharedClientSecretEncryptsAndPersists(): void
    {
        $settings = $this->createMock(SettingRepositoryInterface::class);
        $settings->expects($this->once())
            ->method('set')
            ->with('microsoft_shared_client_secret_enc', 'enc-value', 'setting.microsoft_shared_client_secret_enc')
            ->willReturn(true);

        $crypto = $this->createMock(SettingsCryptoGatewayInterface::class);
        $crypto->expects($this->once())
            ->method('encryptString')
            ->with('secret-value')
            ->willReturn('enc-value');

        $gateway = new SettingsMicrosoftGateway(new SettingsMetadataGateway($settings), $crypto);
        $this->assertTrue($gateway->setMicrosoftSharedClientSecret('secret-value'));
    }
}
