<?php

namespace App\Tests\MessageHandler;

use App\Entity\AppLog;
use App\Entity\User;
use App\Message\AppLogMessage;
use App\MessageHandler\AppLogMessageHandler;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;

class AppLogMessageHandlerTest extends TestCase
{
    public function testInvokeWithUser(): void
    {
        $user = new User();
        $user->setEmail('t@t.com');
        $user->setFirstName('T');
        $user->setLastName('T');
        $user->setPassword('h');

        $userRepo = $this->createStub(UserRepository::class);
        $userRepo->method('find')->willReturn($user);

        $em = $this->createMock(EntityManagerInterface::class);
        $em->expects($this->once())->method('persist')->with($this->isInstanceOf(AppLog::class));
        $em->expects($this->once())->method('flush');

        $handler = new AppLogMessageHandler($em, $userRepo, 'test-secret');
        $message = new AppLogMessage('GET', '/admin', 'app_admin_index', 'Consultation', 1, '127.0.0.1');
        $handler($message);
    }

    public function testInvokeWithoutUser(): void
    {
        $userRepo = $this->createStub(UserRepository::class);

        $em = $this->createMock(EntityManagerInterface::class);
        $em->expects($this->once())->method('persist')->with($this->isInstanceOf(AppLog::class));
        $em->expects($this->once())->method('flush');

        $handler = new AppLogMessageHandler($em, $userRepo, 'test-secret');
        $message = new AppLogMessage('POST', '/admin/sync', 'app_admin_sync_all', 'Synchronisation', null, '10.0.0.1');
        $handler($message);
    }
}
