<?php


namespace AutoAdmin\Bundle\Admin\Controller\Security;

use Exception;
use LogicException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
    #[Route('/login', name: 'aa_admin_login')]
    public function login(AuthenticationUtils $authenticationUtils, RequestStack $requestStack): Response
    {
        $request = $requestStack->getCurrentRequest();

        // cannot use $request->getScheme() because some servers return bullshit schemes
        if (substr($request->getUri(), 0, 7) === 'http') {
            return new RedirectResponse('https://' . substr($request->getUri(), 8));
        }

        $params = [
            // last username entered by the user
            'last_username' => $authenticationUtils->getLastUsername(),
            // get the login error if there is one
            'error' => $authenticationUtils->getLastAuthenticationError(),
        ];

        return $this->render('@AutoAdminAdmin/security/login.html.twig', $params);
    }

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