<?php
namespace PrestaShop\Module\PolarisPrestaConnector\Controller;

use Employee;
use PrestaShop\PrestaShop\Adapter\LegacyContext;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserProviderInterface;

/**
 * CronAuth Listener
 * Pour les installations en v8, il faut bypasser l'authentification classique de Prestashop qui est basée sur une session et un cookie, et qui ne fonctionne pas pour les tâches cron qui sont des requêtes externes sans session ni cookie.
 */
class CronAuthListener
{
    private $legacyContext;
    private $tokenStorage;
    private $userProvider;

    public function __construct(
        LegacyContext $legacyContext,
        TokenStorageInterface $tokenStorage,
        UserProviderInterface $userProvider
    ) {
        $this->legacyContext = $legacyContext;
        $this->tokenStorage = $tokenStorage;
        $this->userProvider = $userProvider;
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        // Si Prestashop 9 alors on sort immédiatement
        if (defined('_PS_VERSION_') && version_compare(_PS_VERSION_, '9.0.0', '>=')) {
            return;
        }

        if (!$event->isMasterRequest()) {
            return;
        }

        $request = $event->getRequest();

        // Uniquement sur la route cron
        if (str_ends_with($request->get('_route'), 'prestaconnector_cron') === false &&
            str_ends_with($request->get('_route'), 'prestaconnector_oidc') === false) {
            return;
        }

        // Initialisation de l'employé dans le contexte legacy
        $context = $this->legacyContext->getContext();
        if (!($context->employee instanceof Employee) || !(int) $context->employee->id) {
            $idEmployee = \Db::getInstance()->getValue(
                'SELECT id_employee FROM ' . _DB_PREFIX_ . 'employee WHERE active = 1 AND id_profile = 1 ORDER BY id_employee ASC'
            );
            if ($idEmployee) {
                $employee = new Employee($idEmployee);
                $context = $this->legacyContext->getContext();
                $context->employee = $employee;

                // Injecter directement dans le SecurityTokenStorage Symfony
                $user = $this->userProvider->loadUserByUsername($employee->email);
                $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
                $this->tokenStorage->setToken($token);
            }
        }        
    }
}