<?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,'competition');
$d=requestJson();
$requestToken=(string)($d['idempotency_key']??($_SERVER['HTTP_IDEMPOTENCY_KEY']??''));
try{
    $c=afCriarCompeticao(
        $pdo,
        (int)$u['id'],
        (string)($d['tipo']??'torneio'),
        (string)($d['nome']??''),
        (string)($d['descricao']??''),
        (int)($d['max_participantes']??4),
        (string)($d['visibilidade']??'publico'),
        $requestToken
    );
    jsonResponse(['ok'=>true,'competicao'=>afCompeticaoPublica($pdo,$c,(int)$u['id'])],201);
}catch(Throwable $e){
    jsonResponse(['ok'=>false,'erro'=>$e->getMessage()],422);
}
