import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import {
  CategoryCount,
  MealCategory,
  RecipeDetail,
  RecipeListItem,
} from '../models/recipe.models';

export interface RecipeQuery {
  category?: MealCategory;
  search?: string;
  ingredient?: string;
}

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

  getRecipes(query: RecipeQuery = {}): Observable<RecipeListItem[]> {
    let params = new HttpParams();
    if (query.category != null) params = params.set('category', query.category);
    if (query.search) params = params.set('search', query.search);
    if (query.ingredient) params = params.set('ingredient', query.ingredient);
    return this.http.get<RecipeListItem[]>('/api/recipes', { params });
  }

  getRecipeById(id: number): Observable<RecipeDetail> {
    return this.http.get<RecipeDetail>(`/api/recipes/${id}`);
  }

  getCategories(): Observable<CategoryCount[]> {
    return this.http.get<CategoryCount[]>('/api/recipes/categories');
  }
}
