<?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', 'productionItems.sourceProduct'])->get($columns);
    }

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

    public function getForProduct(int $productId)
    {
        return $this->model->forProduct($productId)->with([
            'ingredients',
            'recipeIngredients.ingredient',
            'productionItems.sourceProduct',
        ])->get();
    }

    public function getWithIngredients(int $id): ?Recipe
    {
        return $this->model->with([
            'product',
            'ingredients',
            'recipeIngredients.ingredient',
            'recipeIngredients.sizeOption',
            'productionItems.sourceProduct',
            'productionItems.sizeOption',
        ])->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'],
                'option_set_item_id' => $ingredient['option_set_item_id'] ?? null,
                'quantity'           => $ingredient['quantity'],
                'unit'               => $ingredient['unit'] ?? null,
                'notes'              => $ingredient['notes'] ?? null,
            ]);
        }
    }

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

        $recipe->productionItems()->delete();

        foreach ($productionItems as $item) {
            $recipe->productionItems()->create([
                'source_product_id'  => $item['source_product_id'],
                'grams'              => $item['grams'],
                'option_set_item_id' => $item['option_set_item_id'] ?? null,
                'notes'              => $item['notes'] ?? null,
            ]);
        }
    }
}
