<?php

declare(strict_types=1);

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

namespace App\Models;

use App\Business\MasterData\MasterDataDeleteGuard;
use App\Models\Concerns\GeneratesDberpCode;
use App\Models\Concerns\HasDberpAuditTrail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DberpWarehouse extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_warehouses';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'name',
        'warehouse_type',
        'address',
        'country_code',
        'region_id',
        'region_name_snapshot',
        'manager_employee_id',
        'contact_phone',
        'is_default',
        'is_enabled',
        'sort_order',
        'remark',
    ];

    protected static function booted(): void
    {
        static::deleting(function (self $warehouse): void {
            app(MasterDataDeleteGuard::class)->ensureCanDelete($warehouse);
        });

        static::saved(function (self $warehouse): void {
            if (! $warehouse->is_default) {
                return;
            }

            self::query()
                ->whereKeyNot($warehouse->getKey())
                ->where('is_default', true)
                ->update([
                    'is_default' => false,
                    'updated_at' => now(),
                ]);
        });
    }

    protected function casts(): array
    {
        return [
            'region_id' => 'integer',
            'manager_employee_id' => 'integer',
            'is_default' => 'boolean',
            'is_enabled' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

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

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

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

    public function manager(): BelongsTo
    {
        return $this->belongsTo(DberpEmployee::class, 'manager_employee_id');
    }

    public function region(): BelongsTo
    {
        return $this->belongsTo(DberpRegion::class, 'region_id');
    }
}
