<?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\BelongsTo;

class DberpProductSkuSpecValue extends Model
{
    protected $table = 'dberp_product_sku_spec_values';

    protected static function booted(): void
    {
        static::saving(function (self $row): void {
            $value = DberpProductSpecValue::query()->find($row->product_spec_value_id);
            if ($value === null) {
                throw new \InvalidArgumentException((string) __('dberp.errors.sku_spec_value_invalid'));
            }

            $row->setAttribute('product_spec_group_id', $value->product_spec_group_id);

            $sku = DberpProductSku::query()->find($row->product_sku_id);
            if ($sku === null) {
                throw new \InvalidArgumentException((string) __('dberp.errors.sku_spec_value_invalid'));
            }

            $group = DberpProductSpecGroup::query()->find($row->product_spec_group_id);
            if ($group === null || (int) $group->product_id !== (int) $sku->product_id) {
                throw new \InvalidArgumentException((string) __('dberp.errors.sku_spec_value_invalid'));
            }
        });
    }

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

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

    public function productSku(): BelongsTo
    {
        return $this->belongsTo(DberpProductSku::class, 'product_sku_id');
    }

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

    public function specValue(): BelongsTo
    {
        return $this->belongsTo(DberpProductSpecValue::class, 'product_spec_value_id');
    }
}
