<?php
declare(strict_types=1);

namespace App\Game\Controller;

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

    #[Route('/echo', name: 'echo', methods: ['POST'])]
    public function echo(Request $request): JsonResponse
    {
        $raw = (string) $request->getContent();
        $data = null;
        if ($raw !== '') {
            try {
                /** @var array<string,mixed>|null $decoded */
                $decoded = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
                $data = $decoded;
            } catch (\Throwable $e) {
                return $this->json([
                    'ok' => false,
                    'error' => 'Invalid JSON: ' . $e->getMessage(),
                ], Response::HTTP_BAD_REQUEST);
            }
        }

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