<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Monolog;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\MessengerLog;
use Ferienpass\CoreBundle\Repository\MessengerLogRepository;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Level;
use Monolog\LogRecord;
use Symfony\Component\Uid\Uuid;

class MessengerLogHandler extends AbstractProcessingHandler
{
    public function __construct(private readonly MessengerLogRepository $logs, private readonly EntityManagerInterface $entityManager, int|string|Level $level = Level::Debug, bool $bubble = true)
    {
        parent::__construct($level, $bubble);
    }

    protected function write(LogRecord $record): void
    {
        $context = $record->context;
        if (!($context['uuid'] ?? null) instanceof Uuid) {
            return;
        }

        $logEntity = $this->logs->findOneBy(['uuid' => $context['uuid']]);
        if (null !== $logEntity) {
            return;
        }

        $related = [];
        foreach ($context['related'] as $entity => $ids) {
            foreach ((array) $ids as $id) {
                if (str_contains((string) $id, '-')) {
                    // TODO
                    continue;
                }

                $related[] = $this->entityManager->getReference($entity, $id);
            }
        }

        $logEntity = new MessengerLog($context['class'], $related, uuid: $context['uuid']);

        if ($context['group'] ?? null) {
            $logEntity->setGroup($this->logs->findOneBy(['uuid' => $context['group']]));
        }

        $this->entityManager->persist($logEntity);

        if ($this->entityManager->getConnection()->isTransactionActive()) {
            return;
        }

        $this->entityManager->flush();
    }
}
