<?php
require_once __DIR__ . '/../../_bootstrap.php';
require_once ROOT_PATH . '/includes/match_functions.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonResponse(['ok'=>false,'erro'=>'Método não permitido.'],405);
afValidarCsrfApi();
$u = afApiOuSessaoUsuario($pdo);
$d = requestJson();
$sessaoId = preg_replace('/[^a-f0-9]/', '', strtolower((string)($d['sessao_id'] ?? '')));
$safeToken = preg_replace('/[^a-f0-9]/', '', strtolower((string)($d['safe_token'] ?? '')));
if (strlen($sessaoId) !== 48) jsonResponse(['ok'=>false,'erro'=>'Sessão inválida.'],422);
try {
    $p=afBuscarPartidaPorSessao($pdo,(int)$u['id'],$sessaoId);
    if(!$p)throw new RuntimeException('Partida não encontrada.');
    $feature=!empty($p['controlled_event_id'])?'controlled_event_farm':'farm';
    afMinorPolicyApiAssert($pdo,$u,$feature,!empty($p['controlled_event_id'])?['controlled_event_id'=>(int)$p['controlled_event_id']]:[]);
    $safeCamera = afSafeCameraAssertReady($pdo,(int)$u['id'],$sessaoId,$safeToken);
    $p = afAtivarPartida($pdo,(int)$u['id'],(int)$u['dispositivo_id'],$sessaoId);
    jsonResponse(['ok'=>true,'partida'=>afPartidaPublica($p,$pdo),'safe_camera'=>afSafeCameraApiState($safeCamera)]);
} catch (Throwable $e) { jsonResponse(['ok'=>false,'erro'=>$e->getMessage()],422); }
