<?php

namespace Mtc\Modules\B2B\Services;

use Illuminate\Support\Facades\DB;

class PoNumberService
{
    /**
     * Generate a new globally unique PO number.
     * Uses the b2b_po_sequence table for concurrency-safe sequential generation.
     * Format: PO-00001, PO-00002, etc. (prefix configurable via config('b2b.po_prefix'))
     */
    public function generate(): string
    {
        $prefix = config('b2b.po_prefix', 'PO');

        $sequenceId = DB::table('b2b_po_sequence')->insertGetId([
            'created_at' => now(),
        ]);

        return $prefix . '-' . str_pad($sequenceId, 5, '0', STR_PAD_LEFT);
    }
}
