<?php

namespace App\EventListener;

use App\Entity\User;
use App\Entity\Usrlog;
use App\Repository\UsrlogRepository;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;

class UsrlogAuthListener implements EventSubscriberInterface
{
    private UsrlogRepository $usrlogRepository;
    private LoggerInterface $logger;

    public function __construct(UsrlogRepository $usrlogRepository, LoggerInterface $logger)
    {
        $this->usrlogRepository = $usrlogRepository;
        $this->logger = $logger;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            SecurityEvents::INTERACTIVE_LOGIN => 'onLoginSuccess',
        ];
    }

    public function onLoginSuccess(InteractiveLoginEvent $event): void
    {
        $token = $event->getAuthenticationToken();
        $user = $token->getUser();
        if (!$user instanceof User) {
            return;
        }

        $request = $event->getRequest();
        $agent = (string) ($request->headers->get('User-Agent') ?? 'unknown');
        $clientIp = (string) ($request->getClientIp() ?? 'unknown');
        $pcode = (string) $user->getUid();

        $usrlog = new Usrlog();
        $usrlog
            ->setPcode($pcode)
            ->setAgent($agent)
            ->setClientIp($clientIp)
            ->setMethod('вход')
        ;

        try {
            $this->usrlogRepository->add($usrlog);
        } catch (\Throwable $e) {
            $this->logger->error('USRLOG: failed to save login log row', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ]);
        }
    }

}
