import { BarcodeProduct, ItemCategory } from '../types';

const OPEN_FOOD_FACTS_URL = 'https://world.openfoodfacts.org/api/v0/product';

function mapOpenFoodFactsCategory(categories: string): ItemCategory {
  const lower = categories.toLowerCase();
  if (lower.includes('beverage') || lower.includes('food') || lower.includes('snack')) {
    return 'food';
  }
  return 'food'; // Open Food Facts is food-focused; default to food
}

export async function lookupBarcode(barcode: string): Promise<BarcodeProduct | null> {
  const url = `${OPEN_FOOD_FACTS_URL}/${barcode}.json`;
  const res = await fetch(url, {
    headers: { 'User-Agent': 'HouseOrg/1.0 (contact@houseorg.de)' },
  });
  if (!res.ok) throw new Error(`Server-Fehler: ${res.status}`);

  try {
    const data = await res.json();
    if (data.status !== 1 || !data.product) return null;

    const p = data.product;
    const name: string =
      p.product_name_de || p.product_name || p.generic_name || 'Unbekanntes Produkt';
    const description: string =
      p.generic_name_de || p.generic_name || p.ingredients_text_de || '';
    const imageUrl: string | undefined = p.image_front_small_url || p.image_url;
    const categories: string = p.categories ?? '';

    return {
      name,
      description: description.slice(0, 150),
      category: mapOpenFoodFactsCategory(categories),
      barcode,
      imageUrl,
    };
  } catch {
    return null;
  }
}
