/**
 * Variations API Service
 * 
 * Functions for interacting with the variations REST API
 */

import api from './api';
import type { Variation, VariationsResponse, VariationsQueryParams } from '../types/variation';

/**
 * Get variations list with filters
 * 
 * ⚡ Uses FAST API (cache-based) for 100× performance
 */
export async function getVariations(params: VariationsQueryParams = {}): Promise<VariationsResponse> {
  // Build query params - only include truthy values
  const queryParams: Record<string, any> = {
    offset: params.offset || 0,
    limit: params.limit || 100,
  };
  
  // Add optional filters only if they have values
  if (params.search) queryParams.search = params.search;
  if (params.parentId) queryParams.parent_id = params.parentId;
  if (params.stockStatus) queryParams.stock_status = params.stockStatus;
  if (params.attributes) queryParams.attributes = params.attributes;
  if (params.priceMin !== null && params.priceMin !== undefined) queryParams.price_min = params.priceMin;
  if (params.priceMax !== null && params.priceMax !== undefined) queryParams.price_max = params.priceMax;
  if (params.filterSalePrice) queryParams.filter_sale_price = params.filterSalePrice;
  if (params.saleDateFrom) queryParams.sale_date_from = params.saleDateFrom;
  if (params.saleDateTo) queryParams.sale_date_to = params.saleDateTo;
  if (params.onlyActiveSales) queryParams.only_active_sales = params.onlyActiveSales;
  
  // ⚡ FAST API: Use cache-based endpoint (grouped or flat)
  const endpoint = params.groupBy === 'parent' 
    ? '/variations/fast/grouped'
    : '/variations/fast';
  
  const { data } = await api.get<VariationsResponse>(endpoint, {
    params: queryParams,
  });
  
  return data;
}

/**
 * Get single variation by ID
 */
export async function getVariation(id: number): Promise<Variation> {
  const { data } = await api.get<{ success: boolean; data: Variation }>(`/variations/${id}`);
  return data.data;
}

/**
 * Update variation
 */
export async function updateVariation(
  id: number,
  updates: Partial<Variation>
): Promise<Variation> {
  const { data } = await api.put<{ success: boolean; data: Variation }>(
    `/variations/${id}`,
    updates
  );
  return data.data;
}

/**
 * Get variations by IDs
 */
export async function getVariationsByIds(ids: number[]): Promise<Variation[]> {
  const { data } = await api.post<{ success: boolean; data: Variation[] }>(
    '/variations/by-ids',
    { ids }
  );
  return data.data;
}

/**
 * Get product by ID (for parent products)
 */
export async function getProduct(id: number): Promise<any> {
  const { data } = await api.get<{ success: boolean; data: any }>(`/products/${id}`);
  return data.data;
}
