<?php

namespace App\Services;

use App\Models\Setting;
use Illuminate\Support\Facades\DB;

class NumberService
{
    public function next(string $key, string $prefix, int $padding = 6): string
    {
        return DB::transaction(function () use ($key, $prefix, $padding) {
            $setting = Setting::query()->where('key', $key)->lockForUpdate()->first();
            $current = $setting ? (int) $setting->value : 1;
            Setting::put($key, $current + 1, 'sequence');

            return $prefix.str_pad((string) $current, $padding, '0', STR_PAD_LEFT);
        });
    }

    public function invoice(): string
    {
        $prefix = (string) setting('invoice_prefix', 'INV');

        return $this->next('invoice_next_number', $prefix.'-');
    }

    public function payment(): string
    {
        return $this->next('payment_next_number', 'PAY-');
    }

    public function sale(): string
    {
        return $this->next('sale_next_number', 'SAL-');
    }
}
