<?php

declare(strict_types=1);

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');
    }
}
