import { API_CONFIG } from '../constants/config';
import { QueryResult, SecondaryProcessResult, PricingDetailsResult } from '../types';

/**
 * 通用的 API 请求函数
 */
const apiRequest = async <T>(
  endpoint: string,
  data: Record<string, any>
): Promise<{ success: boolean; data: T[]; message: string }> => {
  const response = await fetch(`${API_CONFIG.BASE_URL}${endpoint}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  });
  
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  
  return response.json();
};

/**
 * 执行定价查询
 */
export const executePricingQuery = async (
  packId: string,
  packType: string,
  labels?: Record<string, any>
): Promise<QueryResult[]> => {
  const result = await apiRequest<QueryResult>(
    API_CONFIG.ENDPOINTS.PRICING_QUERY,
    { packId, packType, labels }
  );
  
  if (!result.success) {
    throw new Error(result.message || '查询失败');
  }
  
  return result.data;
};

/**
 * 执行二次工艺查询
 */
export const executeSecondaryProcessQuery = async (
  packId: string,
  packType: string
): Promise<SecondaryProcessResult[]> => {
  const result = await apiRequest<SecondaryProcessResult>(
    API_CONFIG.ENDPOINTS.SECONDARY_PROCESS,
    { packId, packType }
  );
  
  if (!result.success) {
    throw new Error(result.message || '二次工艺查询失败');
  }
  
  return result.data;
};

/**
 * 执行定价详情查询
 */
export const executePricingDetailsQuery = async (
  packId: string
): Promise<PricingDetailsResult[]> => {
  const result = await apiRequest<PricingDetailsResult>(
    API_CONFIG.ENDPOINTS.PRICING_DETAILS,
    { packId }
  );
  
  if (!result.success) {
    throw new Error(result.message || '定价详情查询失败');
  }
  
  return result.data;
};