<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

class CaseNumberService
{
    public function next(int $businessId): string
    {
        return DB::transaction(function () use ($businessId): string {
            DB::table('case_number_sequences')->insertOrIgnore([
                'business_id' => $businessId,
                'next_number' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $sequence = DB::table('case_number_sequences')
                ->where('business_id', $businessId)
                ->lockForUpdate()
                ->first();

            $number = (int) $sequence->next_number;
            DB::table('case_number_sequences')->where('id', $sequence->id)->update([
                'next_number' => $number + 1,
                'updated_at' => now(),
            ]);

            return sprintf('CASE-%d-%06d', $businessId, $number);
        }, 5);
    }
}
