<?php
declare(strict_types=1);

namespace App\Game\Controller;

use App\Game\Entity\Session;
use App\Game\Enum\SessionStatus;
use App\Game\Service\GameResponseService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

#[Route('/game/api', name: 'game_api_')]
final class GameApiController extends AbstractController
{

    public function __construct(
            protected GameResponseService $gameResponseService,
            private EntityManagerInterface $entityManager
    ) {

    }

    #[Route('/ping', name: 'ping', methods: ['GET'])]
    public function ping(): JsonResponse
    {
        return $this->json([
            'ok' => true,
            'service' => 'game-api',
            'ts' => date('c'),
        ]);
    }

    #[Route('/check-finished/{session}', name: 'check_finished', methods: ['POST'])]
    public function checkFinished(Session $session): JsonResponse
    {
        $now = (new \DateTime())->getTimestamp();
        $isFinished = false;

        if ($session->getStatus() === SessionStatus::PLAYING) {
            if ($session->getTimer() !== null && $now >= $session->getTimer()) {
                $session->setStatus(SessionStatus::LOST);
                $this->entityManager->persist($session);
                $this->entityManager->flush();
                $isFinished = true;
            }
        } elseif ($session->getStatus() === SessionStatus::LOST || $session->getStatus() === SessionStatus::WON) {
            $isFinished = true;
        }

        return $this->json([
            'ok' => true,
            'finished' => $isFinished,
            'status' => $session->getStatus()->value,
        ]);
    }

    #[Route('/message', name: 'message', methods: ['POST'])]
    public function message(Request $request): JsonResponse
    {
        $raw = (string) $request->getContent();
        $data = null;
        if ($raw !== '') {
            $data = $this->gameResponseService->getGameResponse($raw);
        }

        return $this->json([
            'ok' => true,
            'result' => $data,
            'ts' => date('c'),
        ]);
    }
}
