<?php

declare(strict_types=1);

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 DberpProductSpecGroup extends Model
{
    use HasDberpAuditTrail;

    protected $table = 'dberp_product_spec_groups';

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

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

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

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

    public function product(): BelongsTo
    {
        return $this->belongsTo(DberpProduct::class, 'product_id');
    }

    public function specValues(): HasMany
    {
        return $this->hasMany(DberpProductSpecValue::class, 'product_spec_group_id');
    }

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

    protected static function booted(): void
    {
        static::deleting(function (DberpProductSpecGroup $group): void {
            if (DberpProductSkuSpecValue::query()->where('product_spec_group_id', $group->getKey())->exists()) {
                throw ValidationException::withMessages([
                    'name' => (string) __('dberp.validation.product_spec_group_delete_blocked_in_use'),
                ]);
            }
        });
    }
}
