<?php

declare(strict_types=1);

namespace App\Game\Controller;

use App\Game\Entity\Session;
use App\Game\Enum\SessionStatus;
use App\Game\Repository\GameRepository;
use App\Game\Repository\SessionRepository;
use App\Tech\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

#[Route('/admin')]
#[IsGranted('ROLE_ADMIN')]
final class GameAdminController extends AbstractController
{
    public function __construct(
        #[Autowire('%kernel.project_dir%')]
        private string $projectDir
    ) {
    }

    #[Route('', name: 'game_admin_dashboard', methods: ['GET'])]
    public function index(
        UserRepository $userRepository,
        SessionRepository $sessionRepository,
        GameRepository $gameRepository,
    ): Response {
        $allUsers = $userRepository->findAll();
        $allSessions = $sessionRepository->findAll();
        $activeSessions = array_filter(
            $allSessions,
            fn(Session $s) => in_array($s->getStatus(), [SessionStatus::CREATED, SessionStatus::READY, SessionStatus::PLAYING])
        );

        return $this->render('game/admin/index.html.twig', [
            'totalUsers'      => count($allUsers),
            'totalPlayers'    => count($userRepository->findByRole('ROLE_PLAYER')),
            'totalAdmins'     => count($userRepository->findByRole('ROLE_ADMIN')),
            'totalGames'      => count($gameRepository->findAll()),
            'totalSessions'   => count($allSessions),
            'activeSessions'  => count($activeSessions),
        ]);
    }

    #[Route('/session/{session}', name: 'game_admin_view_session', methods: ['GET'])]
    public function viewSession(Session $session): Response
    {
        $playersLogs = [];
        foreach ($session->getPlayers() as $player) {
            $username = $player->getUser()->getUsername();
            $logFile = $this->projectDir . '/var/log/sessions/' . $session->getId() . '/' . $username . '.txt';

            $playersLogs[] = [
                'username' => $username,
                'logs' => file_exists($logFile) ? file_get_contents($logFile) : '',
            ];
        }

        return $this->render('game/admin/sessions/view.html.twig', [
            'session' => $session,
            'playersLogs' => $playersLogs,
        ]);
    }
}
