<?php

namespace App\Support;

use App\Models\Branch;
use App\Models\Dealer;

class BranchCodeGenerator
{
    public static function nextForDealer(Dealer $dealer): string
    {
        $dealerCode = (string) $dealer->code;
        $sequence = 1;

        do {
            $candidate = sprintf('%s_BRA-%03d', $dealerCode, $sequence);

            $exists = Branch::withoutGlobalScope('dealer_scope')
                ->where('dealer_id', $dealer->id)
                ->where('code', $candidate)
                ->exists();

            if (! $exists) {
                return $candidate;
            }

            $sequence++;
        } while (true);
    }
}

