<?php

namespace MintyPHP\Tests\Service\Auth;

use MintyPHP\Repository\User\UserExternalIdentityRepositoryInterface;
use MintyPHP\Service\Auth\AuthExternalIdentityGateway;
use PHPUnit\Framework\TestCase;

class AuthExternalIdentityGatewayTest extends TestCase
{
    public function testFindByProviderTidOidDelegatesToRepository(): void
    {
        $row = ['id' => 1, 'user_id' => 42, 'provider' => 'microsoft', 'tid' => 'tenant-abc', 'oid' => 'oid-xyz'];

        $repo = $this->createMock(UserExternalIdentityRepositoryInterface::class);
        $repo->expects($this->once())
            ->method('findByProviderTidOid')
            ->with('microsoft', 'tenant-abc', 'oid-xyz')
            ->willReturn($row);

        $gateway = new AuthExternalIdentityGateway($repo);
        $this->assertSame($row, $gateway->findByProviderTidOid('microsoft', 'tenant-abc', 'oid-xyz'));
    }

    public function testFindByProviderTidOidReturnsNullWhenNotFound(): void
    {
        $repo = $this->createMock(UserExternalIdentityRepositoryInterface::class);
        $repo->expects($this->once())
            ->method('findByProviderTidOid')
            ->with('microsoft', 'unknown-tid', 'unknown-oid')
            ->willReturn(null);

        $gateway = new AuthExternalIdentityGateway($repo);
        $this->assertNull($gateway->findByProviderTidOid('microsoft', 'unknown-tid', 'unknown-oid'));
    }

    public function testFindByProviderIssuerSubjectDelegatesToRepository(): void
    {
        $row = ['id' => 2, 'user_id' => 99, 'provider' => 'oidc', 'issuer' => 'https://issuer.example', 'subject' => 'sub-123'];

        $repo = $this->createMock(UserExternalIdentityRepositoryInterface::class);
        $repo->expects($this->once())
            ->method('findByProviderIssuerSubject')
            ->with('oidc', 'https://issuer.example', 'sub-123')
            ->willReturn($row);

        $gateway = new AuthExternalIdentityGateway($repo);
        $this->assertSame($row, $gateway->findByProviderIssuerSubject('oidc', 'https://issuer.example', 'sub-123'));
    }

    public function testCreateLinkReturnsBool(): void
    {
        $data = ['user_id' => 42, 'provider' => 'microsoft', 'tid' => 'tenant-abc', 'oid' => 'oid-xyz'];

        $repo = $this->createMock(UserExternalIdentityRepositoryInterface::class);
        $repo->expects($this->once())
            ->method('createLink')
            ->with($data)
            ->willReturn(7);

        $gateway = new AuthExternalIdentityGateway($repo);
        $this->assertTrue($gateway->createLink($data));
    }
}
