<?php

declare(strict_types=1);

namespace App\Game\Controller;

use App\Game\Entity\Session;
use App\Game\Enum\SessionStatus;
use App\Game\Repository\SessionRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/admin/sessions')]
#[IsGranted('ROLE_ADMIN')]
final class GameAdminSessionController extends AbstractController
{
    #[Route('', name: 'game_admin_sessions', methods: ['GET'])]
    public function index(SessionRepository $sessionRepository): Response
    {
        return $this->render('game/admin/sessions/index.html.twig', [
            'sessions' => $sessionRepository->findBy([], ['created' => 'DESC']),
        ]);
    }

    #[Route('/{id}/close', name: 'game_admin_session_close', methods: ['POST'])]
    public function close(Session $session, Request $request, EntityManagerInterface $em): Response
    {
        if (!$this->isCsrfTokenValid('close_session_' . $session->getId(), $request->request->get('_token'))) {
            $this->addFlash('danger', 'Invalid CSRF token.');
            return $this->redirectToRoute('game_admin_sessions');
        }

        $session->setStatus(SessionStatus::LOST);
        $em->flush();

        $this->addFlash('success', sprintf('Session #%d closed.', $session->getId()));

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