import { type CreateRecipeInput, createRecipeSchema, type RecipeImportDraftView, } from "@batch-cooking/shared"; /** * Attempts to turn `draft` straight into a submittable {@link CreateRecipeInput} * — no form, no person involved — for the planning picker's transparent * import path (`RecipePickerDialog`'s `handleSelectDraftItem`): adding a * not-yet-imported source item to a planning slot should just work, * silently, whenever nothing about it actually needs a human's judgment * call. Returns `null` the moment anything does — an ingredient line the * automatic matcher (`ingredient-matcher.ts`) couldn't resolve to a real * ingredient/unit/quantity, or a missing portions count — so the caller can * fall back to the full review screen (`ImportRecipePage`), pre-filled from * this exact same draft, for a person to fill in what's missing. * * Default `visibility`/`dietIds` mirror what a person would otherwise leave * untouched on that same form (`PERSONAL`, no diet tags) — nothing here is * a guess about data the draft doesn't have an opinion on. * `createRecipeSchema.safeParse` is still the actual authority on whether * the result is submittable (a positive-portions check, string lengths, * etc.) — the checks above it exist only for what a schema alone can't * catch: `ingredient`/`unit` being resolved references, not just present * values. */ export function tryBuildCompleteImport(draft: RecipeImportDraftView): CreateRecipeInput | null { if (draft.portions === null) return null; if (draft.ingredients.length === 0) return null; if ( draft.ingredients.some( (line) => line.ingredient === null || line.unit === null || line.quantity === null, ) ) { return null; } const candidate: CreateRecipeInput = { name: draft.name, description: draft.description, picture: draft.picture, portions: draft.portions, visibility: "PERSONAL", dietIds: [], ingredients: draft.ingredients.map((line) => ({ // Every line is fully resolved by this point — guarded above. ingredientId: (line.ingredient as NonNullable).id, quantity: line.quantity as number, unitId: (line.unit as NonNullable).id, })), steps: draft.steps.map((step) => ({ description: step.description, picture: step.picture, })), }; const result = createRecipeSchema.safeParse(candidate); return result.success ? result.data : null; }