import { getPlatformAccessToken } from '../lib/authSession';
import type { BacktestRequestPayload, BacktestResult } from './types';
import { tradingRuntime } from '../lib/runtime';
import { createRequestId } from '../../../shared/request-id.js';

export const runBacktestApi = async (payload: BacktestRequestPayload): Promise<BacktestResult> => {
    const accessToken = await getPlatformAccessToken();

    const apiUrl = tradingRuntime.tradingApiUrl;
    const response = await fetch(`${apiUrl}/api/backtest/run`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`,
            'x-request-id': createRequestId('web-backtest')
        },
        body: JSON.stringify(payload)
    });

    const body = await response.json().catch(() => ({} as any));
    if (!response.ok || !body?.success || !body?.result) {
        throw new Error(body?.error || `Backtest request failed (${response.status})`);
    }
    return body.result as BacktestResult;
};
