import api from './api';

export interface Product {
  id: string;
  source: 'cima' | 'openfoodfacts';
  name: string;
  brand: string;
  category: string;
  image_url: string | null;
  active_ingredient?: string;
  dosage?: string;
  form?: string;
  prescription?: string;
  commercialized?: boolean;
  photos?: { tipo: string; url: string }[];
  docs?: { tipo: number; url: string }[];
  nutriscore?: string;
  ingredients?: string;
  nova_group?: number;
  eco_score?: string;
}

export interface ProductSearchResponse {
  results: Product[];
  total: number;
  sources: {
    cima: number;
    openfoodfacts: number;
  };
}

export async function searchProducts(query: string): Promise<Product[]> {
  if (!query || query.trim().length < 2) return [];
  try {
    const { data } = await api.get<ProductSearchResponse>('/products/search', {
      params: { q: query }
    });
    return data.results || [];
  } catch (error) {
    console.error('[Products] Search error:', error);
    return [];
  }
}

export async function getProduct(source: string, id: string): Promise<Product | null> {
  try {
    const { data } = await api.get<Product>(`/products/${source}/${id}`);
    return data;
  } catch (error) {
    console.error('[Products] Detail error:', error);
    return null;
  }
}
