<?php

namespace App\Services\Care;

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

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

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

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

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