<?php

namespace Modular\ConnectorDependencies\Ares\Framework\Foundation\Http;

use Modular\ConnectorDependencies\Illuminate\Support\Facades\Cache;
use Modular\ConnectorDependencies\Illuminate\Support\Facades\Log;
use Modular\ConnectorDependencies\Illuminate\Support\Str;
class HttpUtils
{
    /**
     * Get memory limit in MB.
     *
     * @return int
     */
    public static function currentMemoryLimit(): int
    {
        if (function_exists('ini_get')) {
            $memoryLimit = ini_get('memory_limit');
        } else {
            $memoryLimit = '256M';
        }
        if (!$memoryLimit) {
            $memoryLimit = '256M';
        }
        return $memoryLimit !== -1 ? wp_convert_hr_to_bytes($memoryLimit) : $memoryLimit;
    }
    /**
     * @param bool $inMegabytes
     * @return int
     */
    public static function maxMemoryLimit(bool $inMegabytes = \false): int
    {
        $currentMemoryLimit = HttpUtils::currentMemoryLimit();
        $maxMemoryLimit = defined('WP_MAX_MEMORY_LIMIT') ? \WP_MAX_MEMORY_LIMIT : '512M';
        if (!$maxMemoryLimit || intval($maxMemoryLimit) === -1) {
            // Unlimited, set to 3GB.
            $maxMemoryLimit = '3200M';
        }
        $maxMemoryLimit = wp_convert_hr_to_bytes($maxMemoryLimit);
        if ($maxMemoryLimit > $currentMemoryLimit) {
            $currentMemoryLimit = $maxMemoryLimit;
        }
        return $inMegabytes ? $currentMemoryLimit / 1024 / 1024 : $currentMemoryLimit;
    }
    /**
     * @return bool
     * @deprecated Use isCron() & isAjax() instead.
     */
    public static function isAjax(): bool
    {
        $request = \Modular\ConnectorDependencies\app('request');
        return defined('DOING_AJAX') && \DOING_AJAX && Str::startsWith($request->get('action'), 'modular_');
    }
    /**
     * @return bool
     */
    public static function isCron(): bool
    {
        return defined('DOING_CRON') && \DOING_CRON;
    }
    /**
     * @return bool
     */
    public static function isDirectRequest(): bool
    {
        $request = \Modular\ConnectorDependencies\app('request');
        // Validate that the request method is GET
        if (!$request->isMethod('GET')) {
            return \false;
        }
        $originQuery = $request->has('origin') && $request->get('origin') === 'mo';
        if (!$originQuery) {
            return \false;
        }
        $isFromQuery = $originQuery && $request->has('type');
        // When is wp-load.php request
        if ($isFromQuery) {
            // Validate allowed parameters based on type
            $type = $request->get('type');
            $origin = $request->get('origin');
            $allParams = array_keys($request->query->all());
            // Validate that type only contains allowed values
            $allowedTypes = ['lb', 'request', 'oauth'];
            if (!in_array($type, $allowedTypes, \true)) {
                return \false;
            }
            // Validate that origin is exactly 'mo'
            if ($origin !== 'mo') {
                return \false;
            }
            switch ($type) {
                case 'request':
                    $allowedParams = ['origin', 'type', 'mrid', 'sig'];
                    break;
                case 'lb':
                    $allowedParams = ['origin', 'type', 'nonce'];
                    break;
                case 'oauth':
                    $allowedParams = ['origin', 'code', 'type', 'state'];
                    break;
                default:
                    return \false;
            }
            // Check if all parameters are allowed
            foreach ($allParams as $param) {
                if (!in_array($param, $allowedParams, \true)) {
                    return \false;
                }
            }
            // Validate that parameters are not empty (except state)
            foreach ($allParams as $param) {
                if ($param === 'state') {
                    continue;
                }
                $value = $request->get($param);
                if ($value === null || $value === '') {
                    return \false;
                }
            }
            // Validate that sig parameter and x-mo-Authentication header are mutually exclusive
            $hasSigParam = $request->has('sig');
            $hasAuthHeader = $request->hasHeader('x-mo-authentication');
            if ($hasSigParam && $hasAuthHeader) {
                return \false;
            }
            // Validate required headers for oauth type
            if ($type === 'oauth') {
                if (!$request->hasHeader('x-mo-authentication')) {
                    return \false;
                }
            }
            // Validate required header or parameter for lb type
            if ($type === 'lb') {
                $hasAuthHeader = $request->hasHeader('Authentication');
                $hasNonceParam = $request->has('nonce');
                if (!$hasAuthHeader && !$hasNonceParam) {
                    return \false;
                }
            }
            return \true;
        }
        return \false;
    }
    /**
     * @return bool
     */
    public static function isMultisite()
    {
        return is_multisite();
    }
    /**
     * @return bool
     */
    public static function isMuPlugin()
    {
        return \Modular\ConnectorDependencies\data_get($GLOBALS, 'modular_is_mu_plugin', \false);
    }
    /**
     * @return void
     */
    public static function forceCloseConnection(): void
    {
        ignore_user_abort(\true);
        if (\function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        } elseif (\function_exists('litespeed_finish_request')) {
            litespeed_finish_request();
        }
    }
    /**
     * @return void
     */
    public static function restartQueue(int $timestamp)
    {
        Cache::forever('illuminate:queue:restart', $timestamp);
        Log::info('Broadcasting queue restart signal.');
    }
}
