<?php

namespace NoahVet\Reef\Subscriber\Symfony;

use NoahVet\Reef\Domain\Log\SyslogMessage;
use NoahVet\Reef\Event\AuditEventInterface;
use NoahVet\Reef\Event\CommandAuditEvent;
use NoahVet\Reef\Event\RequestAuditEvent;
use NoahVet\Reef\Factory\SimplePrincipalFactoryInterface;
use NoahVet\Reef\Log\SyslogClientInterface;
use Symfony\Component\DependencyInjection\Attribute\When;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

#[When(env: 'dev')]
#[When(env: 'prod')]
class AuditSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private readonly SimplePrincipalFactoryInterface $simplePrincipalFactory,
        private readonly SyslogClientInterface $syslogClient,
    ) {
    }

    #[\Override]
    public static function getSubscribedEvents(): array
    {
        return [
            CommandAuditEvent::NAME => 'onAuditEvent',
            RequestAuditEvent::NAME => 'onAuditEvent',
        ];
    }

    public function onAuditEvent(AuditEventInterface $event): void
    {
        $this->syslogClient->sendMessage(
            (new SyslogMessage())
                ->setAction($event->getAction())
                ->setResourceType($event->getResourceType())
                ->setEventType($event->getEventType())
                ->setPrincipalId(
                    $this->simplePrincipalFactory->create($event->getAuthenticationType())->getId(),
                )
                ->setExtraData($event->getExtraData()),
        );
    }
}
