<?php

namespace App\Modules\Procurement\Models;

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

class GoodsReceipt extends Model
{
    use BelongsToTenant;

    protected $table = 'goods_receipts';

    protected $fillable = [
        'tenant_id',
        'purchase_order_id',
        'receipt_number',
        'warehouse_id',
        'status',
        'correlation_id',
        'actor_user_id',
        'posted_at',
    ];

    protected function casts(): array
    {
        return [
            'posted_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::updating(function (GoodsReceipt $m): void {
            if ($m->getOriginal('status') === GoodsReceiptLifecycleStatus::Posted->value && $m->isDirty()) {
                throw new RuntimeException('Posted goods receipt is immutable.');
            }
        });
    }

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

    public function warehouse(): BelongsTo
    {
        return $this->belongsTo(Warehouse::class, 'warehouse_id');
    }

    public function items(): HasMany
    {
        return $this->hasMany(GoodsReceiptItem::class, 'goods_receipt_id');
    }
}
