<?php

namespace App\Services\Care;

use App\Models\Organization;
use App\Models\Patient;
use Illuminate\Support\Facades\DB;

class PatientNumberGenerator
{
    public function generate(Organization $organization): string
    {
        $prefix = config('care.patient_number.prefix', 'LC');
        $year = now()->format('Y');

        return DB::transaction(function () use ($organization, $prefix, $year) {
            $latest = Patient::withTrashed()
                ->where('organization_id', $organization->id)
                ->where('patient_number', 'like', "{$prefix}-{$year}-%")
                ->orderByDesc('patient_number')
                ->lockForUpdate()
                ->value('patient_number');

            $sequence = 1;
            if ($latest && preg_match('/-(\d+)$/', $latest, $matches)) {
                $sequence = (int) $matches[1] + 1;
            }

            return sprintf('%s-%s-%05d', $prefix, $year, $sequence);
        });
    }
}
