<?php

namespace App\Service;

use Doctrine\ORM\EntityManagerInterface;
use App\Entity\ActionLog;

class ActionLogger
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function log(string $type, array $data = []): void
    {
        $log = new ActionLog();
        $log->setType($type);
        $log->setData($data);
        $log->setCreatedAt(new \DateTime());

        if (isset($data['from_url'])) {
            $log->setFromUrl($data['from_url']);
        } else if (isset($_SERVER['HTTP_REFERER'])) {
            $log->setFromUrl($_SERVER['HTTP_REFERER']);
        }
        if (isset($data['who'])) {
            $log->setWho($data['who']);
        }
        $this->entityManager->persist($log);
        $this->entityManager->flush();
    }

    /**
     * @return ActionLog[]
     */
    public function getLastLogs(int $limit = 100): array
    {
        return $this->entityManager->getRepository(ActionLog::class)
            ->createQueryBuilder('a')
            ->orderBy('a.createdAt', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }
}
