<?php

namespace App\Repositories\Eloquent;

use App\Models\Recipe;
use Illuminate\Database\Eloquent\Model;

class RecipeRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new Recipe();
    }

    public function all(array $columns = ['*']): \Illuminate\Database\Eloquent\Collection
    {
        return $this->model->with(['product', 'ingredients'])->get($columns);
    }

    public function getActive()
    {
        return $this->model->active()->with(['product', 'ingredients'])->get();
    }

    public function getForProduct(int $productId)
    {
        return $this->model->forProduct($productId)->with('ingredients')->get();
    }

    public function getWithIngredients(int $id): ?Recipe
    {
        return $this->model->with(['product', 'ingredients', 'recipeIngredients.ingredient'])->find($id);
    }

    public function syncIngredients(int $recipeId, array $ingredients): void
    {
        $recipe = $this->find($recipeId);

        // Delete existing recipe ingredients
        $recipe->recipeIngredients()->delete();

        // Add new recipe ingredients
        foreach ($ingredients as $ingredient) {
            $recipe->recipeIngredients()->create([
                'ingredient_id' => $ingredient['ingredient_id'],
                'quantity' => $ingredient['quantity'],
                'unit' => $ingredient['unit'] ?? null,
                'notes' => $ingredient['notes'] ?? null,
            ]);
        }
    }
}
