<?php
use Root\Core\Base;

function GenarateRandomNumber($min = 1, $max = 10000):int
{
    return mt_rand($min,$max);
}

function AL($key, $module = null, $fileName = 'attributes', $lang = null)
{
    $lang = $lang ?: app()->getLocale();
    $modulePath = resolveLangPath($module);

    $filePath = $modulePath . $lang . '/' . $fileName . '.php';

    if (file_exists($filePath)) {
        $file = require $filePath;
        return $file[$key] ?? null;
    }

    return null;
}


function EL($key, $module = null, $fileName = 'errors', $lang = null, array $params = [])
{
    $lang = $lang ?: app()->getLocale();
    $modulePath = resolveLangPath($module);

    $filePath = $modulePath . $lang . '/' . $fileName . '.php';

    if (file_exists($filePath)) {
        $file = require $filePath;
        $errorMSG = $file[$key] ?? null;

        if ($errorMSG !== null && !empty($params)) {
            foreach ($params as $paramKey => $value) {
                $errorMSG = str_replace($paramKey, $value, $errorMSG);
            }
        }

        return $errorMSG;
    }

    return null;
}


function SetLog($data, $dbConnectionName = null)
{
    
    $taskManager = new Base\TaskManager();

    $taskManager->DispatchToQueue(
        $data,
        empty($dbConnectionName) ? $dbConnectionName : CoreConfig('database.log.connectionName','database'), 
        \Root\Core\Jobs\Log::class 
    );

}

function CoreConfig(string $path, $default = null)
{
    static $loadedConfigs = [];

    $segments = explode('.', $path);

    if (count($segments) < 2) {
        throw new InvalidArgumentException("Path باید حداقل شامل نام فایل و کلید باشد.");
    }

    $file = array_shift($segments);

    if (!isset($loadedConfigs[$file])) {
        $configPath = __DIR__ . '/../Config/' . $file . '.php';
        if (file_exists($configPath)) {
            $loadedConfigs[$file] = include $configPath;
        } else {
            $loadedConfigs[$file] = [];
        }
    }

    $config = &$loadedConfigs[$file];

    foreach ($segments as $segment) {
        if (is_array($config) && array_key_exists($segment, $config)) {
            $config = &$config[$segment];
        } else {
            if ($default !== null) {
                $config[$segment] = $default;
                return $default;
            }
            return null;
        }
    }

    return $config;
}

function FileURL(string $id): string 
{
    return rtrim(config('services.file_service.base_url'), '/') . '/' .
    str_replace('{id}', $id, config('services.file_service.path_pattern'));
}

function resolveLangPath(?string $module): string
{
    if ($module === null) {
        return base_path('lang/') ; 
    }

    if (strtolower($module) === 'root') {
        $vendorPath = realpath(__DIR__ . '/../Lang/');
        return $vendorPath ? $vendorPath . '/' : '';
    }

    return base_path('modules/' . ucfirst($module) . '/Lang/');
}

