import { Study, StudyListResponse, HistoryResponse, PruningResponse, StudyStatus } from '../types';

const API_BASE = '/api';

class ApiClient {
  async getStudies(): Promise<StudyListResponse> {
    const response = await fetch(`${API_BASE}/optimization/studies`);
    if (!response.ok) throw new Error('Failed to fetch studies');
    return response.json();
  }

  async getStudyStatus(studyId: string): Promise<StudyStatus> {
    const response = await fetch(`${API_BASE}/optimization/studies/${studyId}/status`);
    if (!response.ok) throw new Error('Failed to fetch study status');
    return response.json();
  }

  async getStudyHistory(studyId: string): Promise<HistoryResponse> {
    const response = await fetch(`${API_BASE}/optimization/studies/${studyId}/history`);
    if (!response.ok) throw new Error('Failed to fetch study history');
    return response.json();
  }

  async getStudyPruning(studyId: string): Promise<PruningResponse> {
    const response = await fetch(`${API_BASE}/optimization/studies/${studyId}/pruning`);
    if (!response.ok) throw new Error('Failed to fetch pruning data');
    return response.json();
  }

  async createStudy(config: any): Promise<{ study_id: string }> {
    const response = await fetch(`${API_BASE}/optimization/studies`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(config),
    });
    if (!response.ok) throw new Error('Failed to create study');
    return response.json();
  }

  async getStudyReport(studyId: string): Promise<{ content: string }> {
    const response = await fetch(`${API_BASE}/optimization/studies/${studyId}/report`);
    if (!response.ok) throw new Error('Failed to fetch report');
    return response.json();
  }

  // Future endpoints for control
  async startOptimization(studyId: string): Promise<void> {
    const response = await fetch(`${API_BASE}/optimization/studies/${studyId}/start`, { method: 'POST' });
    if (!response.ok) throw new Error('Failed to start optimization');
  }

  async stopOptimization(studyId: string): Promise<void> {
    const response = await fetch(`${API_BASE}/optimization/studies/${studyId}/stop`, { method: 'POST' });
    if (!response.ok) throw new Error('Failed to stop optimization');
  }
}

export const apiClient = new ApiClient();