/**
 * Export/Import API Service
 */

import api from './api';
import type { ExportRequest, ExportResponse, ImportResponse } from '../types/export';

/**
 * Export variations to CSV or XLSX
 */
export async function exportVariations(request: ExportRequest): Promise<ExportResponse> {
  const { data } = await api.post<ExportResponse>('/export-import/export', request);
  return data;
}

/**
 * Import variations from file
 */
export async function importVariations(file: File): Promise<ImportResponse> {
  const formData = new FormData();
  formData.append('file', file);
  
  const { data } = await api.post<ImportResponse>('/export-import/import', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
  
  return data;
}

/**
 * Trigger browser download from base64 content
 */
export function downloadFile(filename: string, content: string, contentType: string) {
  // Decode base64
  const byteCharacters = atob(content);
  const byteNumbers = new Array(byteCharacters.length);
  
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  
  const byteArray = new Uint8Array(byteNumbers);
  const blob = new Blob([byteArray], { type: contentType });
  
  // Create download link
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  
  // Cleanup
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
}
