<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\AdminBundle\Controller;

use Serenity\AuthBundle\Form\Type\AdminLoginType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\UX\Turbo\TurboBundle;

class AuthenticationController extends AbstractController
{
    #[Route(path: '/login', name: 'admin_login')]
    public function login(AuthenticationUtils $authenticationUtils, Request $request): Response
    {
        $error = $authenticationUtils->getLastAuthenticationError();
        $lastUsername = $authenticationUtils->getLastUsername();
        $form = $this->createForm(AdminLoginType::class);

        if ('turbo-stream' === $request->getPreferredFormat()) {
            $request->setRequestFormat('html'); // 🔒 forcer HTML
        }
        /* if (TurboBundle::STREAM_FORMAT === $request->getPreferredFormat()) {
             $request->setRequestFormat(TurboBundle::STREAM_FORMAT);

             return new JsonResponse();
         }*/

        return $this->render('@SerenityAdmin/layout/authentication/login.html.twig', [
            'last_username' => $lastUsername,
            'error' => $error,
            'menu' => 'login',
            'form' => $form,
        ]);
    }

    #[Route(path: '/logout', name: 'admin_logout', methods: ['POST', 'GET'])]
    public function logout(): never
    {
        throw new \Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
    }
}
