<?php

namespace App\Services;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class IdGenerator
{
    /**
     * Generate a random ID starting at 4 digits, expanding to 5 if needed
     *
     * @param string $model Model class name
     * @param string $field Field to check for uniqueness
     * @return string
     */
    public static function generate(string $model, string $field): string
    {
        $attempts = 0;
        $maxAttempts = 10;

        while ($attempts < $maxAttempts) {
            // Try 4 digits first
            if ($attempts < 5) {
                $id = (string) random_int(1000, 9999);
            } else {
                // Try 5 digits if all 4-digit numbers are taken
                $id = (string) random_int(10000, 99999);
            }

            if (!$model::where($field, $id)->exists()) {
                return $id;
            }

            $attempts++;
        }

        // If we get here, try a completely random string as fallback
        return Str::random(10);
    }
}