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

export interface StrategyPresetPayload {
  id: string;
  name: string;
  description: string;
  risk_style_id: string;
  recommended_assets: string[];
  typical_trades_per_day: string;
  performance_tag: string;
  is_popular: boolean;
  created_by?: string;
  original_profile_id?: string;
  strategy_config: Record<string, unknown>;
}

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

  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 fetchMarketplacePresets(): Promise<any[]> {
  const response = await apiRequest<{ presets: any[] }>('/api/marketplace-presets');
  return Array.isArray(response.presets) ? response.presets : [];
}

export async function publishMarketplacePreset(payload: StrategyPresetPayload): Promise<void> {
  await apiRequest<{ success: boolean }>('/api/marketplace-presets', {
    method: 'POST',
    body: JSON.stringify(payload),
  });
}
