<?php

namespace App\Models\Purchasing;

use App\Models\Catalog\Product;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\HasDefaultUnitFromProduct;
use App\Models\Lookups\UnitOfMeasure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class PurchaseOrderItem extends Model
{
    use BelongsToTenant, HasDefaultUnitFromProduct;

    public const UPDATED_AT = null;

    protected $fillable = [
        'uuid', 'purchase_order_id', 'product_id', 'unit_id',
        'ordered_quantity', 'received_quantity', 'unit_cost', 'created_by',
    ];

    protected function casts(): array
    {
        return [
            'ordered_quantity' => 'decimal:4',
            'received_quantity' => 'decimal:4',
            'unit_cost' => 'decimal:2',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (self $model): void {
            if (! $model->uuid) {
                $model->uuid = (string) Str::ulid();
            }
        });
    }

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

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

    public function unit(): BelongsTo
    {
        return $this->belongsTo(UnitOfMeasure::class, 'unit_id');
    }

    public function remainingQuantity(): float
    {
        return max(0.0, (float) $this->ordered_quantity - (float) $this->received_quantity);
    }
}
