import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import {
  CreateRecipeInput,
  RecipeDetail,
  RecipeImportResult,
  RecipeMacroRecalcResult,
  RecalculateRecipeCaloriesResult,
} from '../models/recipe.models';

@Injectable({ providedIn: 'root' })
export class RecipeManagementService {
  constructor(private readonly http: HttpClient) {}

  createRecipe(input: CreateRecipeInput): Observable<RecipeDetail> {
    return this.http.post<RecipeDetail>('/api/recipes', this.toPayload(input));
  }

  updateRecipe(id: number, input: CreateRecipeInput): Observable<RecipeDetail> {
    return this.http.put<RecipeDetail>(`/api/recipes/${id}`, this.toPayload(input));
  }

  downloadImportTemplate(): Observable<Blob> {
    return this.http.get('/api/recipes/import/template', { responseType: 'blob' });
  }

  importFromExcel(file: File): Observable<RecipeImportResult> {
    const formData = new FormData();
    formData.append('file', file);
    return this.http.post<RecipeImportResult>('/api/recipes/import/excel', formData);
  }

  recalculateAllMacros(): Observable<RecipeMacroRecalcResult> {
    return this.http.post<RecipeMacroRecalcResult>('/api/recipes/recalculate-macros', {});
  }

  recalculateRecipeCalories(
    recipeId: number,
    targetCalories: number,
    apply = false,
  ): Observable<RecalculateRecipeCaloriesResult> {
    return this.http.post<RecalculateRecipeCaloriesResult>(
      `/api/recipes/${recipeId}/recalculate-calories`,
      { targetCalories, apply },
    );
  }

  private 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,
      })),
    };
  }
}
