import apiClient from './client';
import type { ExitPolicy, PaperTrade } from '../lib/types';

export function listPaperTrades(status?: 'open' | 'closed') {
  return apiClient
    .get<PaperTrade[]>('paper-trades', { params: status ? { status } : {} })
    .then((r) => r.data);
}

export function getExitPolicy() {
  return apiClient.get<ExitPolicy>('paper-trades/exit-policy').then((r) => r.data);
}

export function updateExitPolicy(payload: Partial<ExitPolicy>) {
  return apiClient.put<ExitPolicy>('paper-trades/exit-policy', payload).then((r) => r.data);
}

export interface CreatePaperTradeBody {
  symbol: string;
  direction: 'long' | 'short';
  entry_price: number;
  shares: number;
  stop_loss: number;
  target: number;
}

export function createPaperTrade(body: CreatePaperTradeBody) {
  return apiClient.post<PaperTrade>('paper-trades', body).then((r) => r.data);
}

export interface EquityPoint {
  date: string;
  book_pnl: number;
  benchmark_pnl: number;
}

export function getEquityCurve() {
  return apiClient.get<EquityPoint[]>('paper-trades/equity-curve').then((r) => r.data);
}

export function closePaperTrade(id: number, closePrice?: number) {
  return apiClient
    .post<{ id: number; status: string }>(`paper-trades/${id}/close`, {
      close_price: closePrice ?? null,
    })
    .then((r) => r.data);
}
