<?php

declare(strict_types=1);

namespace App\Models;

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

class OutletProduct extends Model
{
    protected $table = 'outlet_products';

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

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

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

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

    protected $appends = ['last_supplier_id'];

    /**
     * Get the last supplier ID used to restock this product in this outlet.
     */
    public function getLastSupplierIdAttribute(): ?int
    {
        $lastTx = StockTransaction::where('outlet_id', $this->outlet_id)
            ->where('item_type', 'Product')
            ->where('item_id', $this->product_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;
    }
}
