<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Models;

use App\Business\Inventory\Enums\InventoryDocumentStatus;
use App\Models\Concerns\GeneratesDberpCode;
use App\Models\Concerns\HasDberpAuditTrail;
use App\Models\Concerns\HasOptionalLightApprovalRelations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Validation\ValidationException;

class DberpOtherStockInOrder extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;
    use HasOptionalLightApprovalRelations;

    protected $table = 'dberp_other_stock_in_orders';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'warehouse_id',
        'reason',
        'status',
        'business_time',
        'effective_at',
        'voided_at',
        'remark',
    ];

    protected static function booted(): void
    {
        static::deleting(function (self $order): void {
            if ($order->status !== InventoryDocumentStatus::Draft->value) {
                throw ValidationException::withMessages([
                    'status' => __('dberp.errors.inventory_delete_only_draft'),
                ]);
            }
        });
    }

    protected function casts(): array
    {
        return [
            'warehouse_id' => 'integer',
            'business_time' => 'datetime',
            'effective_at' => 'datetime',
            'voided_at' => 'datetime',
        ];
    }

    public function getDberpNumberScope(): string
    {
        return 'stock_in';
    }

    public function getDberpAuditActionPrefix(): string
    {
        return 'dberp.other_stock_in';
    }

    /**
     * @return list<string>
     */
    public function getDberpAuditFields(): array
    {
        return $this->getFillable();
    }

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

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

    protected function lightApprovalDocumentType(): string
    {
        return 'inventory_adjustment';
    }
}
