<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Recipe extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'product_id',
        'name',
        'description',
        'instructions',
        'yield_grams',
        'is_active',
    ];

    protected $casts = [
        'yield_grams' => 'decimal:2',
        'is_active'   => 'boolean',
    ];

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    public function ingredients(): BelongsToMany
    {
        return $this->belongsToMany(Ingredient::class, 'recipe_ingredients')
            ->withPivot(['quantity', 'unit', 'notes'])
            ->withTimestamps();
    }

    public function recipeIngredients(): HasMany
    {
        return $this->hasMany(RecipeIngredient::class);
    }

    /**
     * Production batch deductions defined for this recipe.
     * Each row specifies how many grams to pull from which product's batch,
     * optionally scoped to a specific size option.
     */
    public function productionItems(): HasMany
    {
        return $this->hasMany(RecipeProductionItem::class);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeForProduct($query, $productId)
    {
        return $query->where('product_id', $productId);
    }

    public function calculateCost(): float
    {
        $totalCost = 0;

        foreach ($this->recipeIngredients as $recipeIngredient) {
            $totalCost += $recipeIngredient->quantity * $recipeIngredient->ingredient->cost_per_unit;
        }

        return $this->yield_grams > 0 ? $totalCost / $this->yield_grams : 0;
    }
}
