import { supabase } from '../lib/supabaseClient';
import type { BacktestRequestPayload, BacktestResult } from './types';
import { tradingRuntime } from '../lib/runtime';

export const runBacktestApi = async (payload: BacktestRequestPayload): Promise<BacktestResult> => {
    const { data: sessionData } = await supabase.auth.getSession();
    const accessToken = sessionData.session?.access_token;
    if (!accessToken) {
        throw new Error('Not authenticated');
    }

    const apiUrl = tradingRuntime.tradingApiUrl;
    const response = await fetch(`${apiUrl}/api/backtest/run`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`
        },
        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;
};
