<?php

namespace App\Classes\Modules\Transactions\Services;


use App\Classes\Exceptions\InternalServerErrorException;
use Carbon\Carbon;

class GeneratesTransactionBillNumber
{

    /** @var ChecksIfTransactionBillNumberExists */
    private $checksIfTransactionBillNumberExists;

    /**
     * GeneratesTransactionBillNo constructor.
     * @param ChecksIfTransactionBillNumberExists $checksIfTransactionBillNumberExists
     */
    public function __construct(ChecksIfTransactionBillNumberExists $checksIfTransactionBillNumberExists)
    {
        $this->checksIfTransactionBillNumberExists = $checksIfTransactionBillNumberExists;
    }


    /**
     * @param string $prefix
     * @param Carbon|null $date
     * @return string
     */
    public function execute(string $prefix, ?Carbon $date = null): string {
        if (!$date) {
            $date = Carbon::now();
        }

        $attempt = 0;
        while ($attempt < 10) {  // Retry up to 10 times
            // $billNumber = $prefix . $date->format('Y') . $date->format('m') . '-' . intval(microtime(true));
            $billNumber = $prefix . $date->format('Y') . $date->format('m') . '-' . mt_rand(1000000, 9999999);
            if (!$this->checksIfTransactionBillNumberExists->execute($billNumber)) {
                return $billNumber;
            }
            $attempt++;
        }

        throw new InternalServerErrorException("Unable to generate unique bill number after {$attempt} attempts.");
    }


}
