<?php

declare(strict_types=1);

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

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Validation\ValidationException;

class DberpDictionaryType extends Model
{
    protected $table = 'dberp_dictionary_types';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'name',
        'description',
        'sort_order',
        'is_delete_locked',
    ];

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

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

    protected static function booted(): void
    {
        static::creating(function (): void {
            throw ValidationException::withMessages([
                'code' => [__('dberp.dictionary_type_control.create_forbidden')],
            ]);
        });

        static::updating(function (DberpDictionaryType $type): void {
            if ($type->isDirty('code')) {
                throw ValidationException::withMessages([
                    'code' => [__('dberp.dictionary_type_control.code_immutable')],
                ]);
            }
        });

        static::deleting(function (): void {
            throw ValidationException::withMessages([
                'id' => [__('dberp.dictionary_type_control.delete_forbidden')],
            ]);
        });
    }
}
