import { getPlatformAccessToken } from './authSession';
import { tradingRuntime } from './runtime';
import { createRequestId } from '../../../shared/request-id.js';

export interface PositionsBootstrapResponse {
  entries: any[];
  orders: any[];
  historyTradeKeys: Array<{ trade_id: string; profile_id: string | null }>;
  profiles: any[];
}

async function apiRequest<T>(path: string): Promise<T> {
  const response = await fetch(`${tradingRuntime.tradingApiUrl}${path}`, {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${await getPlatformAccessToken()}`,
      'x-request-id': createRequestId('web-positions'),
    },
  });

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

export async function fetchPositionsBootstrap(options?: { scope?: 'user' | 'all'; limit?: number }): Promise<PositionsBootstrapResponse> {
  const params = new URLSearchParams();
  if (options?.scope === 'all') {
    params.set('scope', 'all');
  }
  if (options?.limit) {
    params.set('limit', String(options.limit));
  }
  const query = params.toString() ? `?${params.toString()}` : '';
  return apiRequest<PositionsBootstrapResponse>(`/api/positions/bootstrap${query}`);
}
