import { apiFetch } from '@/src/api/client';
import type { CreateRecipeInput, RecipeDetail } from '@/src/types/recipe';
import type { RecipeImportResult } from '@/src/types/recipe-management';

function toPayload(input: CreateRecipeInput) {
  return {
    name: input.name,
    mealCategory: input.mealCategory,
    calories: input.calories,
    protein: input.protein,
    fat: input.fat,
    carbs: input.carbs,
    prepTimeMinutes: input.prepTimeMinutes,
    ingredients: input.ingredients.map((i, index) => ({
      name: i.name,
      amountGrams: i.amountGrams,
      unit: i.unit.trim() || null,
      catalogItemId: i.catalogItemId ?? null,
      sortOrder: i.sortOrder || index,
    })),
    steps: input.steps.map((s) => ({
      stepNumber: s.stepNumber,
      description: s.description,
    })),
  };
}

export async function updateRecipe(id: number, input: CreateRecipeInput): Promise<RecipeDetail> {
  return apiFetch<RecipeDetail>(`/recipes/${id}`, { method: 'PUT', body: toPayload(input) });
}

export async function downloadImportTemplate(): Promise<Blob> {
  return apiFetch<Blob>('/recipes/import/template');
}

export async function importRecipesFromExcel(uri: string, fileName: string): Promise<RecipeImportResult> {
  const formData = new FormData();
  formData.append('file', {
    uri,
    name: fileName,
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  } as unknown as Blob);
  return apiFetch<RecipeImportResult>('/recipes/import/excel', {
    method: 'POST',
    body: formData,
  });
}
