import { api } from "./axiosInstance";
import type { RecipeDetail } from "@/types/recipe.types";
import type { CreateRecipeInput, RecipeImportResult, RecipeMacroRecalcResult, RecalculateRecipeCaloriesResult } from "@/types/recipe-management.types";

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,
      sortOrder: i.sortOrder || index,
      catalogItemId: i.catalogItemId ?? null,
    })),
    steps: input.steps.map((s) => ({
      stepNumber: s.stepNumber,
      description: s.description,
    })),
  };
}

export async function createRecipe(input: CreateRecipeInput): Promise<RecipeDetail> {
  const { data } = await api.post<RecipeDetail>("/recipes", toPayload(input));
  return data;
}

export async function updateRecipe(id: number, input: CreateRecipeInput): Promise<RecipeDetail> {
  const { data } = await api.put<RecipeDetail>(`/recipes/${id}`, toPayload(input));
  return data;
}

export async function downloadImportTemplate(): Promise<Blob> {
  const { data } = await api.get<Blob>("/recipes/import/template", {
    responseType: "blob",
  });
  return data;
}

export async function importRecipesFromExcel(file: File): Promise<RecipeImportResult> {
  const formData = new FormData();
  formData.append("file", file);
  const { data } = await api.post<RecipeImportResult>("/recipes/import/excel", formData, {
    headers: { "Content-Type": "multipart/form-data" },
  });
  return data;
}

export async function recalculateAllRecipeMacros(): Promise<RecipeMacroRecalcResult> {
  const { data } = await api.post<RecipeMacroRecalcResult>("/recipes/recalculate-macros");
  return data;
}

export async function recalculateRecipeCalories(
  recipeId: number,
  targetCalories: number,
  apply = false,
): Promise<RecalculateRecipeCaloriesResult> {
  const { data } = await api.post<RecalculateRecipeCaloriesResult>(
    `/recipes/${recipeId}/recalculate-calories`,
    { targetCalories, apply },
  );
  return data;
}
