import api from './api';

export type BrokerAction = 'BUY' | 'SELL';

export interface BrokerProvider {
  id: string;
  name: string;
  description: string;
  docsUrl: string;
  latencyMs: number;
  features: Record<string, boolean>;
  supportsDemo: boolean;
}

export interface BrokerCredentials {
  apiKey: string;
  accountId: string;
  demo?: boolean;
}

export interface BrokerOrder {
  action: BrokerAction;
  symbol: string;
  quantity: number;
  price: number;
  type?: 'MARKET' | 'LIMIT' | 'STOP' | string;
  stopLoss?: number | null;
  takeProfit?: number | null;
}

export interface BrokerPosition {
  symbol: string;
  quantity: number;
  avgPrice: number;
  lastPrice?: number | null;
  pnl?: number | null;
  ticket?: number;
}

export interface BrokerSession {
  provider: BrokerProvider | null;
  account_id?: string;
  balance?: number | null;
  positions?: BrokerPosition[];
  last_heartbeat?: string;
  demo?: boolean;
}

const mapProvider = (provider: any): BrokerProvider => ({
  id: provider.id,
  name: provider.name,
  description: provider.description,
  docsUrl: provider.docs_url,
  latencyMs: provider.latency_ms,
  features: provider.features || {},
  supportsDemo: provider.supports_demo ?? true,
});

const mapSession = (session: any | null): BrokerSession | null => {
  if (!session) return null;
  return {
    provider: session.provider ? mapProvider(session.provider) : null,
    account_id: session.account_id,
    balance: session.balance,
    positions: session.positions || [],
    last_heartbeat: session.last_heartbeat,
    demo: session.demo,
  };
};

export const brokerService = {
  async listProviders(): Promise<BrokerProvider[]> {
    const response = await api.get('/brokers/providers');
    return (response.data || []).map(mapProvider);
  },

  async getSession(): Promise<BrokerSession | null> {
    const response = await api.get('/brokers/session');
    return mapSession(response.data);
  },

  async connect(providerId: string, credentials: BrokerCredentials): Promise<BrokerSession> {
    const response = await api.post('/brokers/connect', {
      provider_id: providerId,
      api_key: credentials.apiKey,
      account_id: credentials.accountId,
      demo: credentials.demo ?? true,
    });
    const session = mapSession(response.data);
    if (!session) {
      throw new Error('Unable to create broker session');
    }
    return session;
  },

  async disconnect(): Promise<void> {
    await api.post('/brokers/disconnect');
  },

  async placeOrder(order: BrokerOrder): Promise<{ remote_id: string; filled: boolean }> {
    const response = await api.post('/brokers/orders', order);
    return response.data;
  },

  async syncPositions(): Promise<{ positions: BrokerPosition[]; balance?: number; lastHeartbeat?: string }> {
    const response = await api.post('/brokers/sync');
    return {
      positions: response.data?.positions || [],
      balance: response.data?.balance,
      lastHeartbeat: response.data?.lastHeartbeat,
    };
  },
};
