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

export interface TradeHistoryApiRow {
  id?: string;
  timestamp?: number | string;
  symbol?: string;
  side?: string;
  size?: number;
  entry_price?: number;
  exit_price?: number;
  pnl?: number;
  pnl_percent?: number;
  reason?: string;
  profile_id?: string | null;
  created_at?: string;
  trade_id?: string;
  source?: string;
}

export async function fetchTradeHistory(options?: { scope?: 'user' | 'all'; limit?: number }): Promise<TradeHistoryApiRow[]> {
  const params = new URLSearchParams();
  if (options?.scope === 'all') {
    params.set('scope', 'all');
  }
  if (options?.limit) {
    params.set('limit', String(options.limit));
  }

  const response = await fetch(`${tradingRuntime.tradingApiUrl}/api/trade-history${params.toString() ? `?${params.toString()}` : ''}`, {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${await getPlatformAccessToken()}`,
      'x-request-id': createRequestId('web-history'),
    },
  });

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