export type PosCatalogItem = {
  id: number;
  type: string;
  name: string;
  sku?: string | null;
  barcode?: string | null;
  price: number;
  track_inventory: boolean;
  stock_available: number | null;
};

export type PosCartLine = {
  service_product_id: number | null;
  name: string;
  type: string;
  unit_price: number;
  quantity: number;
  track_inventory: boolean;
  stock_available: number | null;
};

export function isServiceProduct(product: Pick<PosCatalogItem, 'type'> | null | undefined) {
  return String(product?.type || '').toLowerCase() === 'service';
}

export function productRequiresStock(product: Pick<PosCatalogItem, 'type' | 'track_inventory'> | null | undefined) {
  if (!product) return false;
  if (isServiceProduct(product)) return false;
  return Boolean(product.track_inventory);
}

export function productStockAvailable(product: Pick<PosCatalogItem, 'track_inventory' | 'stock_available' | 'type'>) {
  if (!productRequiresStock(product)) return null;
  return product.stock_available ?? 0;
}

export function canAddProductToCart(
  product: Pick<PosCatalogItem, 'type' | 'track_inventory' | 'stock_available'>,
  quantity = 1,
) {
  if (!productRequiresStock(product)) return true;
  const available = productStockAvailable(product);
  return available === null || available >= quantity;
}

export function formatMoney(value: number | string | null | undefined) {
  return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'PHP' }).format(Number(value) || 0);
}
