/**
 * Cloudflare Workers Environment Access
 *
 * Centralizes access to Workers bindings via globalThis.env.
 * This keeps runtime-specific globals out of adapters/drivers.
 */
const getWorkersEnv = () => {
    const env = globalThis.env;
    if (env === undefined || env === null)
        return null;
    if (typeof env !== 'object')
        return null;
    return env;
};
const getD1Binding = (config) => {
    if (config.d1 !== undefined && config.d1 !== null)
        return config.d1;
    const env = getWorkersEnv();
    const candidateNames = ['DB', 'zintrust_db', getWorkersVar('D1_BINDING') ?? ''].filter((name, idx, arr) => name.trim() !== '' && arr.indexOf(name) === idx);
    if (env !== null) {
        for (const name of candidateNames) {
            const binding = env[name];
            if (binding !== undefined && binding !== null)
                return binding;
        }
    }
    const globalRef = globalThis;
    for (const name of candidateNames) {
        const binding = globalRef[name];
        if (binding !== undefined && binding !== null)
            return binding;
    }
    return null;
};
const getKVBinding = (bindingName) => {
    const env = getWorkersEnv();
    if (env === null)
        return null;
    const resolvedName = typeof bindingName === 'string' && bindingName.trim() !== ''
        ? bindingName
        : getWorkersVar('KV_NAMESPACE') ?? 'CACHE';
    const kv = env[resolvedName];
    return kv ?? null;
};
const getR2Binding = (bindingName) => {
    const env = getWorkersEnv();
    if (env === null)
        return null;
    if (typeof bindingName === 'string' && bindingName.trim() !== '') {
        return env[bindingName] ?? null;
    }
    const defaultNames = ['R2_BUCKET', 'R2', 'BUCKET'];
    for (const name of defaultNames) {
        const binding = env[name];
        if (binding !== undefined && binding !== null)
            return binding;
    }
    return null;
};
const getWorkersVar = (key) => {
    const env = getWorkersEnv();
    if (env === null)
        return null;
    const value = env[key];
    if (value === undefined || value === null)
        return null;
    if (typeof value === 'string')
        return value;
    return String(value);
};
const getAssetsBinding = () => {
    const env = getWorkersEnv();
    if (env === null)
        return null;
    const binding = env['ASSETS'];
    if (binding && typeof binding.fetch === 'function')
        return binding;
    return null;
};
const isCloudflareSocketsEnabled = () => {
    const raw = getWorkersVar('ENABLE_CLOUDFLARE_SOCKETS');
    if (raw === null)
        return false;
    const normalized = raw.trim().toLowerCase();
    if (normalized === '')
        return false;
    return normalized === 'true' || normalized === '1';
};
export const Cloudflare = Object.freeze({
    getWorkersEnv,
    getD1Binding,
    getKVBinding,
    getR2Binding,
    getAssetsBinding,
    getWorkersVar,
    isCloudflareSocketsEnabled,
});
