<?php

namespace App\Behavior;

use Doctrine\DBAL\Connection;
use App\Traits\SerializerTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Authentication\AuthenticationSuccessHandler as LexikAuthenticationSuccessHandler;

class UserAuth extends LexikAuthenticationSuccessHandler
{
    use SerializerTrait;
    private $databaseConnection;

    public function __construct(
        JWTTokenManagerInterface $jwtManager,
        EventDispatcherInterface $dispatcher,
        Connection $databaseConnection
    )
    {
        $this->databaseConnection = $databaseConnection;
        parent::__construct($jwtManager, $dispatcher);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token): Response
    {
        $sql = $this->databaseConnection->executeQuery(sprintf('
                SELECT is_active FROM user
                WHERE id = %s
            ', $token->getUser()->getId())
        );
        $isVerified = $sql->fetchAll()[0]['is_active'];

        if ((bool) $isVerified === false){
            $response = [
                'status' => Response::HTTP_UNAUTHORIZED,
                'error'  => false,
                'data'   => '',
            ];
            return $this->sendResponse($response, ['groups' => 'user']);
        }

        $this->databaseConnection->exec(sprintf('
                UPDATE user
                SET last_login = now()
                WHERE (id = %s)
            ', $token->getUser()->getId())
        );

        return parent::onAuthenticationSuccess($request, $token);
    }
}