<?php

namespace Daniv04\HaciendaPackage\Services\Utils;

use Daniv04\HaciendaPackage\Services\ConsecutiveNumberService;

class ConsecutiveGeneratorService
{
    public function __construct(
        private ConsecutiveNumberService $consecutiveNumberService
    ) {}

    /**
     * Genera un consecutivo único y seguro usando contador global
     *
     * @param string $branch Sucursal (3 dígitos)
     * @param string $pos Terminal/POS (5 dígitos)
     * @param string $receiptType Tipo de comprobante (FE, TE, NC, etc.)
     * @return string Consecutivo formateado (XXX-XXXXX-XX-XXXXXXXXXX)
     */
    public function generateConsecutive(string $branch, string $pos, string $receiptType): string
    {
        $consecutiveNumber = $this->consecutiveNumberService->getIncrementedConsecutiveNumber();
        
        return $this->format($branch, $pos, $receiptType, $consecutiveNumber);
    }

    
    private function format(
        string $branch,
        string $pos,
        string $receiptType,
        string $consecutiveNumber
    ): string {
        return sprintf(
            '%s-%s-%s-%s',
            str_pad($branch, 3, '0', STR_PAD_LEFT),
            str_pad($pos, 5, '0', STR_PAD_LEFT),
            str_pad($receiptType, 2, '0', STR_PAD_LEFT),
            str_pad($consecutiveNumber, 10, '0', STR_PAD_LEFT)
        );
    }
}