<?php

namespace App\Support;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

/**
 * Shared by MainCategory/SubCategory (and any future model with the same
 * pattern) — ported from the near-identical private generateSortCode()
 * methods duplicated across leolanka-inertia's MainCategoryController and
 * SubCategoryController. Same algorithm, one call site: uppercase, strip
 * non-letters, first 5 chars (falling back to $default), then append an
 * incrementing counter on collision, checked against soft-deleted rows too.
 */
class SortCodeGenerator
{
    /**
     * @param  class-string<Model>  $modelClass
     */
    public static function generate(string $modelClass, string $name, string $default): string
    {
        $base = substr(Str::upper(preg_replace('/[^A-Za-z]/i', '', $name) ?? ''), 0, 5) ?: $default;
        $code = $base;
        $counter = 1;

        while ($modelClass::withTrashed()->where('sort_code', $code)->exists()) {
            $code = $base.($counter++);
        }

        return $code;
    }
}
