<?php

declare(strict_types=1);

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

namespace App\Models;

use App\Models\Concerns\HasDberpAuditTrail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Validation\ValidationException;

class DberpProductSpecValue extends Model
{
    use HasDberpAuditTrail;

    protected $table = 'dberp_product_spec_values';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'product_spec_group_id',
        'value_label',
        'sort_order',
    ];

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

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

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

    public function specGroup(): BelongsTo
    {
        return $this->belongsTo(DberpProductSpecGroup::class, 'product_spec_group_id');
    }

    public function skuSpecAssignments(): HasMany
    {
        return $this->hasMany(DberpProductSkuSpecValue::class, 'product_spec_value_id');
    }

    protected static function booted(): void
    {
        static::deleting(function (DberpProductSpecValue $value): void {
            if (DberpProductSkuSpecValue::query()->where('product_spec_value_id', $value->getKey())->exists()) {
                throw ValidationException::withMessages([
                    'value_label' => (string) __('dberp.validation.product_spec_value_delete_blocked_in_use'),
                ]);
            }
        });
    }
}
