import type { DataClearType, PipelineJobResult, PipelineStatsResult } from '../types';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';

class PipelineApiService {
  private async request<T = unknown>(endpoint: string, options?: RequestInit): Promise<T> {
    const url = `${API_BASE_URL}/pipeline${endpoint}`;

    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        ...options?.headers,
      },
      ...options,
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || `HTTP ${response.status}: ${response.statusText}`);
    }

    return data;
  }

  // Symbol sync operations
  async syncQMSymbols(): Promise<PipelineJobResult> {
    return this.request<PipelineJobResult>('/symbols', { method: 'POST' });
  }

  async syncProviderSymbols(provider: string): Promise<PipelineJobResult> {
    return this.request<PipelineJobResult>(`/symbols/${provider}`, { method: 'POST' });
  }

  // Exchange sync operations
  async syncQMExchanges(): Promise<PipelineJobResult> {
    return this.request<PipelineJobResult>('/exchanges', { method: 'POST' });
  }

  async syncAllExchanges(clearFirst: boolean = false): Promise<PipelineJobResult> {
    const params = clearFirst ? '?clear=true' : '';
    return this.request<PipelineJobResult>(`/exchanges/all${params}`, { method: 'POST' });
  }

  // Provider mapping sync operations
  async syncQMProviderMappings(): Promise<PipelineJobResult> {
    return this.request<PipelineJobResult>('/provider-mappings/qm', { method: 'POST' });
  }

  async syncIBExchanges(): Promise<PipelineJobResult> {
    return this.request<PipelineJobResult>('/provider-mappings/ib', { method: 'POST' });
  }

  // Status and maintenance operations
  async getSyncStatus(): Promise<PipelineJobResult> {
    return this.request<PipelineJobResult>('/status');
  }

  async clearPostgreSQLData(dataType: DataClearType = 'all'): Promise<PipelineJobResult> {
    const params = `?type=${dataType}`;
    return this.request<PipelineJobResult>(`/clear/postgresql${params}`, { method: 'POST' });
  }

  // Statistics operations
  async getExchangeStats(): Promise<PipelineStatsResult> {
    return this.request<PipelineStatsResult>('/stats/exchanges');
  }

  async getProviderMappingStats(): Promise<PipelineStatsResult> {
    return this.request<PipelineStatsResult>('/stats/provider-mappings');
  }
}

// Export singleton instance
export const pipelineApi = new PipelineApiService();
