/**
 * Data Import Service - Mirror backend data import endpoints
 */
import { apiClient } from '../client';
import { 
  ImportValidationRequest, 
  ImportValidationResponse, 
  ImportProcessRequest, 
  ImportProcessResponse,
  ImportStatusResponse
} from '../types/dataImport';

export class DataImportService {
  private readonly baseUrl = '/tenants';

  async validateJsonData(
    tenantId: string, 
    data: any
  ): Promise<ImportValidationResponse> {
    return apiClient.post<ImportValidationResponse>(
      `${this.baseUrl}/${tenantId}/sales/import/validate-json`, 
      data
    );
  }

  async validateCsvFile(
    tenantId: string, 
    file: File
  ): Promise<ImportValidationResponse> {
    const formData = new FormData();
    formData.append('file', file);
    
    return apiClient.uploadFile<ImportValidationResponse>(
      `${this.baseUrl}/${tenantId}/sales/import/validate-csv`,
      formData
    );
  }

  async importJsonData(
    tenantId: string, 
    data: any,
    options?: {
      skip_validation?: boolean;
      chunk_size?: number;
    }
  ): Promise<ImportProcessResponse> {
    const payload = {
      ...data,
      options,
    };
    return apiClient.post<ImportProcessResponse>(
      `${this.baseUrl}/${tenantId}/sales/import/json`, 
      payload
    );
  }

  async importCsvFile(
    tenantId: string, 
    file: File,
    options?: {
      skip_validation?: boolean;
      chunk_size?: number;
    }
  ): Promise<ImportProcessResponse> {
    const formData = new FormData();
    formData.append('file', file);
    if (options) {
      formData.append('options', JSON.stringify(options));
    }

    return apiClient.uploadFile<ImportProcessResponse>(
      `${this.baseUrl}/${tenantId}/sales/import/csv`,
      formData
    );
  }

  async getImportStatus(
    tenantId: string, 
    importId: string
  ): Promise<ImportStatusResponse> {
    return apiClient.get<ImportStatusResponse>(
      `${this.baseUrl}/${tenantId}/sales/import/${importId}/status`
    );
  }

  async cancelImport(
    tenantId: string, 
    importId: string
  ): Promise<{ success: boolean; message: string }> {
    return apiClient.post<{ success: boolean; message: string }>(
      `${this.baseUrl}/${tenantId}/sales/import/${importId}/cancel`
    );
  }

  async getImportHistory(tenantId: string): Promise<ImportStatusResponse[]> {
    return apiClient.get<ImportStatusResponse[]>(
      `${this.baseUrl}/${tenantId}/sales/import/history`
    );
  }
}

export const dataImportService = new DataImportService();