import type { IngredientView } from "@batch-cooking/shared";

/**
 * Sentinel `id` for a placeholder ingredient line the user just added in
 * the recipe form but that has **no database row yet** — the API creates
 * the real `Ingredient` row (with a real id) when the recipe is saved (see
 * `recipe.service.ts`'s `resolveIngredientLines`). Never sent to the API:
 * the submit payload uses `placeholderName`, not `ingredientId`, for these
 * lines. Kept out of `excludeIds`/duplicate checks by testing
 * `isPlaceholder` rather than the id.
 */
export const UNSAVED_PLACEHOLDER_ID = 0;

/**
 * Builds the in-memory {@link IngredientView} for a brand-new placeholder
 * line (the "add « … » as an ingredient to complete" action in
 * `IngredientPicker`). Shaped exactly like what the API returns for a
 * placeholder once persisted — `isPlaceholder: true`, the typed text as
 * `displayName`, a generic `JAR` icon, default aisle, no allergen/diet
 * info — so `IngredientRow` renders it through the same path as an
 * edit-loaded placeholder with no special-casing.
 */
export function makePlaceholderIngredientView(name: string): IngredientView {
  return {
    id: UNSAVED_PLACEHOLDER_ID,
    key: "",
    icon: "JAR",
    category: "dryGoods",
    subcategory: "other",
    reproducible: false,
    allergens: [],
    diets: [],
    isPlaceholder: true,
    displayName: name,
  };
}

/**
 * Whether this line is a placeholder the user just added that has **no
 * database row yet** — the submit payload must describe it with
 * `placeholderName` (asking the API to create the row) rather than
 * `ingredientId`. An *edit-loaded* placeholder fails this test: it already
 * has a real id and round-trips as a normal `{ ingredientId }` line, so
 * editing a recipe never spawns a duplicate placeholder row.
 */
export function isUnsavedPlaceholder(
  ingredient: Pick<IngredientView, "id" | "isPlaceholder">,
): boolean {
  return ingredient.isPlaceholder && ingredient.id === UNSAVED_PLACEHOLDER_ID;
}
