<?php
require __DIR__.'/_bootstrap.php';

use Zoo\Database;
use Zoo\Auth\PlayerAuthService;
use Zoo\Game\BetService;
use Zoo\Wallet\WalletQuery;

try {
    $in=input_json();
    $db=Database::connect();
    $player=(new PlayerAuthService($db))->authenticate($in);

    $roundId=(int)($in['round_id'] ?? 0);
    $area=(string)($in['area'] ?? '');
    $amount=(float)($in['amount'] ?? 0);
    $requestId=(string)($in['request_id'] ?? '');

    if($roundId<=0) throw new RuntimeException('round_id is required');
    if($requestId==='') throw new RuntimeException('request_id is required');

    $bet=(new BetService($db))->place(
        (int)$player['user_id'],
        $roundId,
        $area,
        $amount,
        $requestId
    );
    $wallet=(new WalletQuery($db))->get((int)$player['user_id']);

    json_out([
        'ok'=>true,
        'player'=>[
            'user_id'=>(int)$player['user_id'],
            'public_id'=>$player['public_id'],
            'account_type'=>$player['account_type'],
            'auth_mode'=>$player['auth_mode']
        ],
        'bet'=>$bet,
        'wallet'=>$wallet
    ],201);
} catch(Throwable $e) {
    json_out(['ok'=>false,'error'=>$e->getMessage()],422);
}
