<?php

namespace App\Modules\Procurement\Models;

use App\Modules\Admin\Tenancy\Traits\BelongsToTenant;
use App\Modules\Procurement\Support\GoodsReceiptLifecycleStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use RuntimeException;

class GoodsReceiptItem extends Model
{
    use BelongsToTenant;

    protected $table = 'goods_receipt_items';

    protected $fillable = [
        'tenant_id',
        'goods_receipt_id',
        'purchase_order_item_id',
        'quantity_received',
        'quarantined_at',
        'integrity_violation_code',
    ];

    protected function casts(): array
    {
        return [
            'quarantined_at' => 'datetime',
            'quantity_received' => 'decimal:4',
        ];
    }

    protected static function booted(): void
    {
        static::updating(function (GoodsReceiptItem $line): void {
            $rid = (int) $line->goods_receipt_id;
            $st = GoodsReceipt::withoutGlobalScopes()->whereKey($rid)->value('status');
            if ($st === GoodsReceiptLifecycleStatus::Posted->value) {
                throw new RuntimeException('Posted receipt lines are immutable.');
            }
        });
    }

    public function goodsReceipt(): BelongsTo
    {
        return $this->belongsTo(GoodsReceipt::class, 'goods_receipt_id');
    }

    public function purchaseOrderItem(): BelongsTo
    {
        return $this->belongsTo(PurchaseOrderItem::class, 'purchase_order_item_id');
    }
}
