import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import {
  IngredientCategory,
  IngredientNutritionItem,
  UpsertIngredientNutritionItemInput,
} from '../models/ingredient-catalog.models';

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

  getCategories(): Observable<IngredientCategory[]> {
    return this.http.get<IngredientCategory[]>('/api/ingredient-catalog/categories');
  }

  getItems(categoryCode?: string, search?: string): Observable<IngredientNutritionItem[]> {
    let params = new HttpParams();
    if (categoryCode) params = params.set('category', categoryCode);
    if (search) params = params.set('search', search);
    return this.http.get<IngredientNutritionItem[]>('/api/ingredient-catalog', { params });
  }

  getItem(id: number): Observable<IngredientNutritionItem> {
    return this.http.get<IngredientNutritionItem>(`/api/ingredient-catalog/${id}`);
  }

  createItem(input: UpsertIngredientNutritionItemInput): Observable<IngredientNutritionItem> {
    return this.http.post<IngredientNutritionItem>('/api/ingredient-catalog', input);
  }

  updateItem(id: number, input: UpsertIngredientNutritionItemInput): Observable<IngredientNutritionItem> {
    return this.http.put<IngredientNutritionItem>(`/api/ingredient-catalog/${id}`, input);
  }

  deleteItem(id: number): Observable<void> {
    return this.http.delete<void>(`/api/ingredient-catalog/${id}`);
  }
}
