<?php

namespace App\Services;

use App\Models\MarketingRequest;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class RequestNumberService
{
    public static function generateNumber(): string
    {
        return DB::transaction(function () {
            $year = Carbon::now()->format('Y');
            $prefix = "HRQ-{$year}-";

            $latestRequest = MarketingRequest::where('request_number', 'like', "{$prefix}%")
                ->orderBy('id', 'desc')
                ->lockForUpdate()
                ->first();

            if ($latestRequest) {
                $lastNumberStr = str_replace($prefix, '', $latestRequest->request_number);
                $nextSequence = ((int) $lastNumberStr) + 1;
            } else {
                $nextSequence = 1;
            }

            return $prefix . str_pad($nextSequence, 4, '0', STR_PAD_LEFT);
        });
    }
}
