import { apiFetch, photoFormPart } from './client';
import { ProductCardData, ProductMacros } from './productCard';

export type FoodLookupItem = {
  label: string;
  meta: string | null;
  refs: Record<string, string>;
  referenceQty: string;
  macros: ProductMacros;
};

// Fiche produit (photo, Nutri-Score, synthèse) partagée avec le scan code-barres
// de "Mon suivi" — voir `api/productCard.ts` et `components/ProductCard.tsx`.
export type ProductCard = ProductCardData;

export type FoodLookupResults = {
  ciqual: FoodLookupItem[];
  openFoodFacts: FoodLookupItem[];
  product: ProductCard | null;
};

export type FoodLookupHistoryEntry = {
  id: number;
  label: string;
  query: string | null;
  barcode: string | null;
  isBarcode: boolean;
  createdAt: string;
};

export type FoodLookupPayload = {
  query: string;
  results: FoodLookupResults | null;
  notice: string | null;
  history: FoodLookupHistoryEntry[];
};

export function lookupFood(params: { q?: string; code?: string; fromScan?: boolean }) {
  const search = new URLSearchParams();
  if (params.q) search.set('q', params.q);
  if (params.code) search.set('code', params.code);
  if (params.fromScan) search.set('fromScan', '1');
  return apiFetch<FoodLookupPayload>(`/food-lookup?${search.toString()}`);
}

export async function identifyFoodPhoto(photoUri: string) {
  const formData = new FormData();
  formData.append('photo', await photoFormPart(photoUri));
  return apiFetch<{ name: string; confidence: number }>('/food-lookup/photo', { method: 'POST', body: formData });
}
