/*
 * The till's product mapping: the one place an API product becomes a till product. Every load (the first one, the
 * reload after a sale, the secondary screens) uses it, because hand-rolled copies drifted into live bugs (services
 * rejected as out of stock, barcode scanning lost after the first sale). Add new product fields here.
 */

/** A product as the API returns it, as far as the till reads it. */
export type ApiProduct = {
  id: number;
  name: string;
  sellPrice: number | string;
  stock: number;
  costPrice?: number | string | null;
  shelfLocation?: string | null;
  category: string;
  imageUrl?: string | null;
  requiresRx?: boolean;
  barcode?: string | null;
  expiryDate?: string | null;
  type?: string;
  code?: string | null;
  unit?: string | null;
  manageStock?: boolean;
};

export interface Product { id: number; name: string; price: number; stock: number; category: string; image: string; rx?: boolean; costPrice?: number; shelfLocation?: string; barcode?: string; expiryDate?: string | null; isService?: boolean; code?: string; unit?: string; manageStock?: boolean; }

/** Single source of truth for API product -> till Product. Keep every load using this. */
export const mapProduct = (p: ApiProduct): Product => ({
  id: p.id,
  name: p.name,
  price: parseFloat(String(p.sellPrice)),
  stock: p.stock,
  costPrice: parseFloat(String(p.costPrice || 0)),
  shelfLocation: p.shelfLocation || "",
  category: p.category,
  image: p.imageUrl || "",
  rx: p.requiresRx,
  barcode: p.barcode || "",
  expiryDate: p.expiryDate || null,
  isService: p.type === "Service",
  // Inventory API plan: shown on the till's product tiles
  code: p.code || "",
  unit: p.unit || "",
  manageStock: p.manageStock !== false,
});
