<?php
declare(strict_types=1);

require __DIR__ . '/common.php';
$env = gobao_load_env();
$userId = gobao_request_user_id($env, 'main');

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $sessionId = gobao_safe_session_id($userId . '_' . (string)($_GET['sessionId'] ?? 'orders'));
    $limit = (int)($_GET['limit'] ?? 50);
    gobao_ok([
        'sessionId' => $sessionId,
        'orders' => gobao_list_orders($sessionId, $limit),
        'database' => gobao_db_counts(),
    ]);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    gobao_fail('POST required', 405);
}

$input = gobao_json_input();
if (!is_array($input) || count($input) === 0) {
    gobao_fail('order body is required');
}

$input['sessionId'] = gobao_safe_session_id($userId . '_' . (string)($input['sessionId'] ?? 'orders'));
$saved = gobao_store_order($input);
gobao_ok([
    'order' => $saved,
    'database' => gobao_db_counts(),
]);
