<?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\HasMany;

class StockLedger extends Model
{
    use HasFactory;

    protected $fillable = [
        'branch_id',
        'ingredient_id',
        'quantity',
        'reserved_quantity',
        'average_cost',
        'last_restocked_at',
    ];

    protected $casts = [
        'quantity' => 'decimal:4',
        'reserved_quantity' => 'decimal:4',
        'average_cost' => 'decimal:2',
        'last_restocked_at' => 'datetime',
    ];

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

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

    public function transactions(): HasMany
    {
        return $this->hasMany(StockTransaction::class, 'ingredient_id', 'ingredient_id')
            ->where('branch_id', $this->branch_id);
    }

    public function getAvailableQuantity(): float
    {
        return $this->quantity - $this->reserved_quantity;
    }

    public function isLowStock(): bool
    {
        return $this->quantity <= $this->ingredient->reorder_level;
    }

    public function isOutOfStock(): bool
    {
        return $this->getAvailableQuantity() <= 0;
    }

    public function scopeForBranch($query, int $branchId)
    {
        return $query->where('branch_id', $branchId);
    }

    public function scopeLowStock($query)
    {
        return $query->whereHas('ingredient', function ($q) {
            $q->whereColumn('stock_ledgers.quantity', '<=', 'ingredients.reorder_level');
        });
    }
}
