<?php

namespace NoahVet\Reef\Test\A_Unit\Subscriber\Symfony;

use NoahVet\Reef\Domain\Log\SimplePrincipal;
use NoahVet\Reef\Domain\Log\SyslogMessageInterface;
use NoahVet\Reef\Event\CommandAuditEvent;
use NoahVet\Reef\Factory\SimplePrincipalFactoryInterface;
use NoahVet\Reef\Log\SyslogClientInterface;
use NoahVet\Reef\Subscriber\Symfony\AuditSubscriber;
use PHPUnit\Framework\TestCase;

class AuditSubscriberTest extends TestCase
{
    public function testOnAuditEvent(): void
    {
        $simplePrincipalFactory = $this->createMock(SimplePrincipalFactoryInterface::class);

        $syslogClient = $this->createMock(SyslogClientInterface::class);

        $subscriber = new AuditSubscriber(
            $simplePrincipalFactory,
            $syslogClient,
        );

        $event = new CommandAuditEvent(
            'reef:iam:principal:perm:grant',
            'reef:iam:principal:8ff3fdbe-ffca-4c1b-80a5-ecfd55748940',
            'reef:iam:principal',
            'Grant permission to principal',
            [
                'granted_permission' => 'reef:iam:principal:perm:edit',
                'granted_to' => 'reef:iam:principal:45c7e84e-991a-48e9-b0c5-2713909a4ddb',
                'grant_type' => '1',
            ],
        );

        $simplePrincipalFactory
            ->expects(self::once())
            ->method('create')
            ->with('service_authentication')
            ->willReturn(new SimplePrincipal('45c7e84e-991a-48e9-b0c5-2713909a4ddb'))
        ;

        $syslogClient
            ->expects(self::once())
            ->method('sendMessage')
            ->with(
                self::callback(
                    static fn (SyslogMessageInterface $syslogMessage): bool => 'reef:iam:principal:perm:grant' === $syslogMessage->getAction()
                            && 'reef:iam:principal' === $syslogMessage->getResourceType()
                            && 'reef.audit.command' === $syslogMessage->getEventType()
                            && '45c7e84e-991a-48e9-b0c5-2713909a4ddb' === $syslogMessage->getPrincipalId()
                            && $syslogMessage->getExtraData() === [
                                'granted_permission' => 'reef:iam:principal:perm:edit',
                                'granted_to' => 'reef:iam:principal:45c7e84e-991a-48e9-b0c5-2713909a4ddb',
                                'grant_type' => '1',
                            ],
                ),
            )
        ;

        $subscriber->onAuditEvent($event);
    }
}
