<?php

namespace App\Classes\Modules\Orders\Services;


class GeneratesOrderNumber
{

    /** @var ChecksIfOrderNumberExists */
   private $checkIfOrderNumberExists;

    /**
     * GeneratesBookingMarking constructor.
     * @param ChecksIfOrderNumberExists $checkIfOrderNumberExists
     */
    public function __construct(ChecksIfOrderNumberExists $checkIfOrderNumberExists)
    {
        $this->checkIfOrderNumberExists = $checkIfOrderNumberExists;
    }


    /**
     * @param null|string $prefix
     * @param int|null $length
     * @return string
     */
    public function execute(?string $prefix = '', ?int $length = 9): string {

        $reference = $prefix.rand((int)('1'.str_repeat(0, $length - 2).'1'), (int) str_repeat(9, $length));
        return !$this->checkIfOrderNumberExists->execute($reference) ? $reference : self::execute();
    }

}