<?php
/**
 * Cloudflare 全局配置检测（cong.php 三项均为可选）
 */
class CloudflareConfig
{
    /** @var array<string,mixed> CLI 回归用覆盖项（enabled / server_ip） */
    private static $testOverrides = [];

    public static function setTestOverrides(array $overrides)
    {
        self::$testOverrides = $overrides;
    }

    public static function clearTestOverrides()
    {
        self::$testOverrides = [];
    }

    public static function apiToken()
    {
        return defined('CLOUDFLARE_API_TOKEN') ? trim((string) CLOUDFLARE_API_TOKEN) : '';
    }

    public static function accountId()
    {
        return defined('CLOUDFLARE_ACCOUNT_ID') ? trim((string) CLOUDFLARE_ACCOUNT_ID) : '';
    }

    public static function serverIp()
    {
        if (array_key_exists('server_ip', self::$testOverrides)) {
            return trim((string) self::$testOverrides['server_ip']);
        }
        return defined('SERVER_IP') ? trim((string) SERVER_IP) : '';
    }

    /**
     * Token + Account ID 均已配置时启用 Cloudflare 自动化
     */
    public static function isEnabled()
    {
        if (array_key_exists('enabled', self::$testOverrides)) {
            return (bool) self::$testOverrides['enabled'];
        }
        return self::apiToken() !== '' && self::accountId() !== '';
    }

    public static function statusLabel($status)
    {
        $map = [
            'local'        => '本地登记',
            'pending_ns'   => '待检测',
            'provisioning' => '配置中',
            'ready'        => '已生效',
            'error'        => '失败',
        ];
        return $map[$status] ?? (string) $status;
    }

    public static function parseNameservers($json)
    {
        if ($json === null || $json === '') {
            return [];
        }
        $decoded = json_decode($json, true);
        return is_array($decoded) ? $decoded : [];
    }
}

if (!function_exists('cloak_cloudflare_enabled')) {
    function cloak_cloudflare_enabled()
    {
        return CloudflareConfig::isEnabled();
    }
}
