// Ce que Dolibarr retourne (simplifié)
export interface DolibarrProduct {
  id:           number;
  ref:          string;
  label:        string;
  description?:  string | null;
  note_public?: string | null;
  price?:        string | null;
  price_ttc?:    string | null;   // ← peut être null
  stock_reel:   number | null;   // ← peut être null
  photos?:      { photo: string }[];
  array_options?: {
    options_categorie?:      string;
    options_souscategorie?:  string;
  };
}

// Ce qu'on envoie au frontend (propre, sans données internes Dolibarr)
export interface Product {
  id:          number;
  ref:         string;
  name:        string;
  description: string;
  price:       string;
  stock:       number;
  inStock:     boolean;
  img:       string | null;
  category:      string;
  subCategory:   string;
}

export const toProduct = (d: DolibarrProduct): Product => {
  // Dolibarr peut envoyer price_ttc, price, ou les deux selon la config TVA
  const rawPrice = d.price_ttc ?? d.price ?? '0';
  const parsed   = parseFloat(String(rawPrice).replace(',', '.'));

  // stock_reel peut être null, undefined ou string selon le module stock
  const rawStock = d.stock_reel ?? 0;
  const parsedStock = Number(rawStock);
  const stock = isNaN(parsedStock) ? 0 : parsedStock;

  return {
    id:          d.id,
    ref:         d.ref          ?? '',
    name:        d.label        ?? '',
    description: d.note_public ?? d.description ?? '',
    price:       isNaN(parsed) ? 'Prix sur demande' : `${parsed.toFixed(2)}€`,
    stock,
    inStock:     stock > 0,
    img:         d.photos?.[0]?.photo ?? null,
    category:    d.array_options?.options_categorie     ?? 'Autres',
    subCategory: d.array_options?.options_souscategorie  ?? '',
  };
};