<?php

namespace App\Services;

use App\Models\Branch;
use App\Models\NumberSequence;
use Illuminate\Support\Facades\DB;

class NumberGenerator
{
    public function customer(Branch $branch): string
    {
        $year = (int) now()->format('Y');

        return DB::transaction(function () use ($branch, $year): string {
            $sequence = NumberSequence::query()
                ->where('type', 'customer')
                ->where('branch_id', $branch->id)
                ->where('year', $year)
                ->lockForUpdate()
                ->first();

            if (! $sequence) {
                $sequence = NumberSequence::create([
                    'type' => 'customer',
                    'branch_id' => $branch->id,
                    'year' => $year,
                    'current_value' => 0,
                ]);
            }

            $sequence->increment('current_value');
            $value = $sequence->fresh()->current_value;

            return sprintf('CUS-%s-%d-%06d', strtoupper($branch->code), $year, $value);
        }, 3);
    }
}
