<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class OutletIngredient extends Model
{
    protected $table = 'outlet_ingredients';

    protected $fillable = [
        'outlet_id',
        'ingredient_id',
        'stock_qty',
        'threshold_qty',
    ];

    protected $casts = [
        'stock_qty' => 'decimal:4',
        'threshold_qty' => 'decimal:4',
    ];

    /**
     * Get the outlet associated with the stock record.
     */
    public function outlet(): BelongsTo
    {
        return $this->belongsTo(Outlet::class);
    }

    /**
     * Get the ingredient associated with the stock record.
     */
    public function ingredient(): BelongsTo
    {
        return $this->belongsTo(Ingredient::class);
    }

    protected $appends = ['last_supplier_id'];

    /**
     * Get the last supplier ID used to restock this ingredient in this outlet.
     */
    public function getLastSupplierIdAttribute(): ?int
    {
        $lastTx = StockTransaction::where('outlet_id', $this->outlet_id)
            ->where('item_type', 'Ingredient')
            ->where('item_id', $this->ingredient_id)
            ->whereNotNull('supplier_id')
            ->latest()
            ->first();

        return $lastTx ? (int)$lastTx->supplier_id : null;
    }

    /**
     * Check if stock level is running low (below safety threshold).
     */
    public function isLowStock(): bool
    {
        return $this->stock_qty <= $this->threshold_qty;
    }
}
