<?php

namespace App\Controller;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
    #[Route(path: '/login', name: 'app_login')]
    public function login(AuthenticationUtils $authenticationUtils,EntityManagerInterface $em): Response
    {
        if($this->getUser()){
            return $this->redirectToRoute('app_accueil');
        }

        // Créer un utilisateur admin par défaut s'il n'existe pas
        $userRepository = $em->getRepository(User::class);
        $adminUser = $userRepository->findOneBy(['pseudo' => 'admin']);

        if(!$adminUser){
            $user = new User();
            $user->setRoles(["ROLE_ADMIN","ROLE_USER"]);
            $user->setPseudo("admin");
            $user->setPassword('$2y$13$CVJ/Hm29HJ3ehPrqrtMl8Oya55d/ZXwlhfL6D2TsWI238bHAqtCrS');
            $user->setDefaultpwd(true);
            $em->persist($user);
            $em->flush();
        }

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();


        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', [
            'last_username' => $lastUsername,
            'error' => $error,
        ]);
    }

    #[Route(path: '/logout', name: 'app_logout')]
    public function logout(): void
    {
        throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
    }
}
