<?php

declare(strict_types=1);

namespace App\Models\Concerns;

use App\Business\SystemRule\NumberSequenceAllocator;

/**
 * 商品品牌编码（brand_code）按编号规则自动生成；留空时在 creating 阶段分配。
 */
trait GeneratesDberpBrandCode
{
    public static function bootGeneratesDberpBrandCode(): void
    {
        static::creating(function ($model): void {
            $code = trim((string) ($model->getAttribute('brand_code') ?? ''));

            if ($code !== '' || ! method_exists($model, 'getDberpNumberScope')) {
                return;
            }

            $scope = $model->getDberpNumberScope();

            if ($scope === null || $scope === '') {
                return;
            }

            $allocated = app(NumberSequenceAllocator::class)->reserveByAppliesTo($scope);

            if ($allocated === null) {
                $scopeLabel = __('dberp.options.number_applies_to')[$scope] ?? $scope;

                throw new \RuntimeException((string) __('dberp.errors.number_rule_missing', ['scope' => $scopeLabel]));
            }

            $model->setAttribute('brand_code', $allocated);
        });
    }
}
