import type { Database } from 'sql.js';
import { RecipeRepository } from '../repositories/RecipeRepository.js';
import type { Recipe, CreateRecipeInput, UpdateRecipeInput, RecipeFilters } from '../types/recipe.js';

export class RecipeService {
  private repository: RecipeRepository;
  constructor(db: Database) { this.repository = new RecipeRepository(db); }
  list(filters: RecipeFilters = {}): { recipes: Recipe[]; total: number } {
    const recipes = this.repository.findAll(filters);
    const total = this.repository.count(filters);
    return { recipes, total };
  }
  get(id: number): Recipe | null { return this.repository.findById(id); }
  create(input: CreateRecipeInput): Recipe {
    if (!input.title.trim()) throw new Error('Recipe title cannot be empty');
    if (!input.ingredients.length) throw new Error('At least one ingredient');
    if (!input.steps.length) throw new Error('At least one step');
    return this.repository.create(input);
  }
  update(id: number, input: UpdateRecipeInput): Recipe | null {
    if (input.title !== undefined && !input.title.trim()) throw new Error('Recipe title cannot be empty');
    if (input.ingredients !== undefined && !input.ingredients.length) throw new Error('At least one ingredient');
    if (input.steps !== undefined && !input.steps.length) throw new Error('At least one step');
    return this.repository.update(id, input);
  }
  delete(id: number): boolean { return this.repository.delete(id); }
}
