<?php

declare(strict_types=1);

namespace Tvdt\Controller\Backoffice;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Requirement\Requirement;
use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Tvdt\Controller\AbstractController;
use Tvdt\Entity\Elimination;
use Tvdt\Entity\Quiz;
use Tvdt\Entity\Season;
use Tvdt\Enum\FlashType;
use Tvdt\Factory\EliminationFactory;
use Tvdt\Security\Voter\SeasonVoter;

final class PrepareEliminationController extends AbstractController
{
    public function __construct(private readonly EliminationFactory $eliminationFactory, private readonly EntityManagerInterface $em) {}

    #[IsCsrfTokenValid('prepare_elimination')]
    #[IsGranted(SeasonVoter::ELIMINATION, 'quiz')]
    #[Route(
        '/backoffice/season/{seasonCode:season}/quiz/{quiz}/elimination/prepare',
        name: 'tvdt_prepare_elimination',
        requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'quiz' => Requirement::UUID],
        methods: ['POST'],
    )]
    public function index(Season $season, Quiz $quiz): RedirectResponse
    {
        $elimination = $this->eliminationFactory->createEliminationFromQuiz($quiz);

        return $this->redirectToRoute('tvdt_prepare_elimination_view', ['elimination' => $elimination->id]);
    }

    #[IsCsrfTokenValid('prepare_elimination', methods: ['POST'])]
    #[IsGranted(SeasonVoter::ELIMINATION, 'elimination')]
    #[Route(
        '/backoffice/elimination/{elimination}',
        name: 'tvdt_prepare_elimination_view',
        requirements: ['elimination' => Requirement::UUID],
        methods: ['GET', 'POST'],
    )]
    public function viewElimination(Elimination $elimination, Request $request): Response
    {
        if ($request->isMethod('POST')) {
            $elimination->updateFromInputBag($request->request);
            $this->em->flush();

            if ($request->request->getBoolean('start')) {
                return $this->redirectToRoute('tvdt_elimination', ['elimination' => $elimination->id]);
            }

            $this->addFlash(FlashType::Success, 'Elimination updated');

            return $this->redirectToRoute('tvdt_prepare_elimination_view', ['elimination' => $elimination->id]);
        }

        return $this->render('backoffice/prepare_elimination/index.html.twig', [
            'controller_name' => 'PrepareEliminationController',
            'elimination' => $elimination,
        ]);
    }
}
