<?php declare(strict_types=1);
/**
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Controller;

use App\Entity\PlayedGame;
use App\Repository\PlayedGameRepository;
use App\Service\ResolveUserNamesService;
use App\Util\RpcManager;
use App\Util\TopicManager;
use DateTimeInterface;
use Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Attribute\Route;

/**
 * Class MercureController
 *
 * Handles HTTP API endpoints that replace the former WebSocket RPC and Topic handlers.
 * Client → Server communication is via HTTP POST/GET.
 * Server → Client broadcasting is via Mercure (SSE).
 *
 * @package  App\Controller
 * @author   Lang <https://www.splendidbear.org>
 * @category Class
 * @license  https://www.gnu.org/licenses/lgpl-3.0.en.html GNU Lesser General Public License
 * @link     www.splendidbear.org
 * @since    2026. 04. 09.
 */
#[AsController]
class MercureController extends AbstractController
{
    public function __construct(
        private readonly TopicManager            $topicManager,
        private readonly RpcManager              $rpcManager,
        private readonly ResolveUserNamesService $userNamesService,
    ) {
    }

    #[Route('/api/game/start', name: 'MineSeekerBundle_api_game_start', methods: ['POST'])]
    public function start(Request $request): JsonResponse
    {
        try {
            $data = $request->toArray();
            $result = $this->rpcManager->saveGrid($data['gameAssoc']);

            return $this->json(['success' => $result]);
        } catch (Exception $e) {
            return $this->json(
                ['success' => false, 'error' => 'Failed to start game: ' . $e->getMessage()],
                Response::HTTP_INTERNAL_SERVER_ERROR
            );
        }
    }

    #[Route('/api/game/connect/{gameAssoc}', name: 'MineSeekerBundle_api_game_connect', methods: ['GET'])]
    public function connect(string $gameAssoc): Response
    {
        try {
            $payload = $this->rpcManager->getConnectInformation($gameAssoc);
            return new Response($payload, Response::HTTP_OK, ['Content-Type' => 'text/plain']);
        } catch (Exception $e) {
            return new Response('', Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    #[Route('/api/game/join/{gameAssoc}', name: 'MineSeekerBundle_api_game_join', methods: ['POST'])]
    public function join(string $gameAssoc): JsonResponse
    {
        $this->topicManager->subscribe($gameAssoc, $this->userNamesService->resolveUserName());

        return $this->json(['success' => true]);
    }

    #[Route('/api/game/step/{gameAssoc}', name: 'MineSeekerBundle_api_game_step', methods: ['POST'])]
    public function step(string $gameAssoc, Request $request): JsonResponse
    {
        $result = $this->topicManager->publish($gameAssoc, $this->userNamesService->resolveUserName(), $request->toArray());

        return $this->json($result);
    }

    #[Route('/api/game/leave/{gameAssoc}', name: 'MineSeekerBundle_api_game_leave', methods: ['POST'])]
    public function leave(string $gameAssoc): JsonResponse
    {
        $this->topicManager->unSubscribe($gameAssoc, $this->userNamesService->resolveUserName());

        return $this->json(['success' => true]);
    }

    #[Route('/api/game/challenge/{targetGameAssoc}', name: 'MineSeekerBundle_api_game_challenge', methods: ['POST'])]
    public function challenge(string $targetGameAssoc, Request $request): JsonResponse
    {
        $data = $request->toArray();
        $challengerGameAssoc = $data['challengerGameAssoc'] ?? '';
        $this->topicManager->publishChallenge($targetGameAssoc, $challengerGameAssoc);

        return $this->json(['success' => true]);
    }

    #[Route(
        '/api/game/challenge/respond/{challengerGameAssoc}',
        name: 'MineSeekerBundle_api_game_challenge_respond',
        methods: ['POST'],
    )]
    public function challengeRespond(string $challengerGameAssoc, Request $request): JsonResponse
    {
        $data = $request->toArray();
        $accepted = (bool)($data['accepted'] ?? false);
        $targetGameAssoc = $data['targetGameAssoc'] ?? '';
        $this->topicManager->publishChallengeResponse($challengerGameAssoc, $accepted, $targetGameAssoc);

        return $this->json(['success' => true]);
    }

    #[Route('/api/game/heartbeat/{gameAssoc}', name: 'MineSeekerBundle_api_game_heartbeat', methods: ['POST'])]
    public function heartbeat(string $gameAssoc, Request $request): JsonResponse
    {
        $data = $request->toArray();
        $color = $data['color'] ?? '';

        if ('red' !== $color && 'blue' !== $color) {
            return $this->json(['success' => false], Response::HTTP_BAD_REQUEST);
        }

        $this->topicManager->publishHeartbeat($gameAssoc, $color);

        return $this->json(['success' => true]);
    }

    #[Route('/api/game/waiting', name: 'MineSeekerBundle_api_game_waiting', methods: ['GET'])]
    public function waiting(PlayedGameRepository $repo): JsonResponse
    {
        $games = $repo->findWaitingGames();

        $result = array_map(static function (PlayedGame $g): array {
            $name = match (true) {
                null !== $g->red     => $g->red->getUsername(),
                null !== $g->redAnon => $g->redAnon->userName,
                null !== $g->blue    => $g->blue->getUsername(),
                default              => $g->blueAnon?->userName ?? 'Unknown',
            };

            return [
                'gameAssoc' => $g->gameAssoc,
                'name'      => $name,
                'since'     => $g->created?->format(DateTimeInterface::ATOM) ?? '',
            ];
        }, $games);

        return $this->json($result);
    }
}
