<?php

namespace App\Controller;

use App\Entity\User;
use App\Service\ConcessionsProvider;
use App\Service\UserValidationMailer;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\Attribute\IsGranted;

/**
 * Inscription : choix du groupe + concessions par un nouvel utilisateur, puis attente de validation.
 */
#[IsGranted('ROLE_USER')]
final class OnboardingController extends AbstractController
{
    #[Route('/bienvenue', name: 'app_onboarding', methods: ['GET', 'POST'])]
    public function onboarding(
        Request $request,
        ConcessionsProvider $provider,
        EntityManagerInterface $em,
        UserValidationMailer $mailer,
        LoggerInterface $logger,
    ): Response {
        /** @var User $user */
        $user = $this->getUser();

        // Déjà actif → accueil ; demande déjà soumise → écran d'attente.
        if ($user->isActive()) {
            return $this->redirectToRoute('app_home');
        }
        if (User::STATUS_ONBOARDING !== $user->getStatus()) {
            return $this->redirectToRoute('app_waiting');
        }

        if ($request->isMethod('POST')) {
            if (!$this->isCsrfTokenValid('onboarding', (string) $request->request->get('_token'))) {
                $this->addFlash('error', 'Jeton de sécurité invalide. Réessayez.');

                return $this->redirectToRoute('app_onboarding');
            }

            $group = (string) $request->request->get('group', '');
            $concessions = $request->request->all('concessions');
            $concessions = \is_array($concessions) ? $concessions : [];

            $validConcessions = array_values(array_filter(
                array_map(static fn ($c) => \is_string($c) ? $c : null, $concessions),
                static fn (?string $c) => null !== $c && $provider->isValid($c),
            ));

            if (!\in_array($group, User::REQUESTABLE_GROUPS, true)) {
                $this->addFlash('error', 'Veuillez choisir un groupe valide.');

                return $this->redirectToRoute('app_onboarding');
            }
            if ([] === $validConcessions) {
                $this->addFlash('error', 'Veuillez sélectionner au moins une concession.');

                return $this->redirectToRoute('app_onboarding');
            }

            $user->setRequestedRole($group)
                ->setConcessions($validConcessions)
                ->setStatus(User::STATUS_PENDING);
            $em->flush();

            try {
                $url = $this->generateUrl('app_users', [], UrlGeneratorInterface::ABSOLUTE_URL);
                $mailer->sendValidationRequest($user, $url);
            } catch (\Throwable $e) {
                $logger->error('Envoi email validation', ['exception' => $e]);
            }

            return $this->redirectToRoute('app_waiting');
        }

        return $this->render('auth/onboarding.html.twig', [
            'concessions' => $provider->all(),
            'groups' => User::REQUESTABLE_GROUPS,
            'groupLabels' => User::GROUP_LABELS,
        ]);
    }

    #[Route('/en-attente', name: 'app_waiting', methods: ['GET'])]
    public function waiting(): Response
    {
        /** @var User $user */
        $user = $this->getUser();

        if ($user->isActive()) {
            return $this->redirectToRoute('app_home');
        }
        if (User::STATUS_ONBOARDING === $user->getStatus()) {
            return $this->redirectToRoute('app_onboarding');
        }

        return $this->render('auth/waiting.html.twig', [
            'refused' => User::STATUS_REFUSED === $user->getStatus(),
        ]);
    }
}
