<?php

declare(strict_types=1);

namespace App\Models\Concerns;

use App\Business\SystemRule\NumberSequenceAllocator;

trait GeneratesDberpCode
{
    public static function bootGeneratesDberpCode(): void
    {
        static::creating(function ($model): void {
            $code = trim((string) ($model->getAttribute('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('code', $allocated);
        });
    }
}