/**
 * 环境变量管理工具类
 */

// 获取环境变量，如果不存在则返回默认值
const getEnvVar = (key, defaultValue = '') => {
    const value = import.meta.env[key]
    return value !== undefined ? value : defaultValue
}

// 系统配置
export const getAppTitle = () => getEnvVar('VITE_APP_TITLE', '维机云供应链')
export const getApiBaseUrl = () => getEnvVar('VITE_APP_API_BASE_URL', 'http://localhost:3000')
export const getAutoLogoutTime = () => parseInt(getEnvVar('VITE_APP_AUTO_LOGOUT_TIME', '1800'))
export const getTokenKey = () => getEnvVar('VITE_APP_TOKEN_KEY', 'jifuyun_token')
export const getUserKey = () => getEnvVar('VITE_APP_USER_KEY', 'jifuyun_user')

// 界面配置
export const getLogoPath = () => getEnvVar('VITE_APP_LOGO_PATH', '/jifu.png')
export const getCollapsedWidth = () => parseInt(getEnvVar('VITE_APP_COLLAPSED_WIDTH', '60'))
export const getExpandedWidth = () => parseInt(getEnvVar('VITE_APP_EXPANDED_WIDTH', '200'))

// 其他配置
export const isDebug = () => getEnvVar('VITE_APP_DEBUG', 'false') === 'true'

// 运行时配置存储
const runtimeConfig = new Map()

// 更新运行时配置
export const setRuntimeConfig = (key, value) => {
    runtimeConfig.set(key, value)
    // 可以在这里添加配置持久化逻辑，比如存储到 localStorage
    try {
        localStorage.setItem(`runtime_${key}`, JSON.stringify(value))
    } catch (error) {
        console.error('Failed to save runtime config:', error)
    }
}

// 获取运行时配置
export const getRuntimeConfig = (key, defaultValue = null) => {
    // 优先从运行时配置中获取
    if (runtimeConfig.has(key)) {
        return runtimeConfig.get(key)
    }
    
    // 尝试从 localStorage 中恢复配置
    try {
        const savedValue = localStorage.getItem(`runtime_${key}`)
        if (savedValue !== null) {
            const value = JSON.parse(savedValue)
            runtimeConfig.set(key, value)
            return value
        }
    } catch (error) {
        console.error('Failed to load runtime config:', error)
    }
    
    return defaultValue
}

// 清除运行时配置
export const clearRuntimeConfig = (key) => {
    runtimeConfig.delete(key)
    try {
        localStorage.removeItem(`runtime_${key}`)
    } catch (error) {
        console.error('Failed to clear runtime config:', error)
    }
}

// 清除所有运行时配置
export const clearAllRuntimeConfig = () => {
    runtimeConfig.clear()
    try {
        Object.keys(localStorage).forEach(key => {
            if (key.startsWith('runtime_')) {
                localStorage.removeItem(key)
            }
        })
    } catch (error) {
        console.error('Failed to clear all runtime config:', error)
    }
}