<?php
require __DIR__.'/_bootstrap.php';
use Zoo\Database;
use Zoo\Auth\UserAuthService;
use Zoo\Wallet\WalletQuery;

function bearer_token(): string {
    $h = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    if (stripos($h,'Bearer ')===0) return trim(substr($h,7));
    return (string)($_SERVER['HTTP_X_USER_SESSION'] ?? '');
}

try {
    $db=Database::connect();
    $user=(new UserAuthService($db))->authenticate(
        bearer_token(),$_SERVER['HTTP_USER_AGENT']??null,$_SERVER['REMOTE_ADDR']??null
    );
    $wallet=(new WalletQuery($db))->get((int)$user['user_id']);
    json_out(['ok'=>true,'user'=>$user,'wallet'=>$wallet]);
} catch(Throwable $e) {
    json_out(['ok'=>false,'error'=>$e->getMessage()],401);
}
