const API = require('../../../lib/API')
const AccessControl = require('../../../lib/AccessControl')
const { BaseStdResponse } = require('../../../BaseStdResponse')
const { CONFIG_KEYS, getAllRuntimeConfigs, saveRuntimeConfig, selectRuntimeConfig } = require('../../../lib/RuntimeConfig')

async function checkAdmin(uuid, session) {
    if (!await AccessControl.checkSession(uuid, session)) return false
    const permissions = await AccessControl.getPermission(uuid)
    return permissions.includes('admin') || permissions.includes('server')
}

class GetRuntimeConfig extends API {
    constructor() { super(); this.setPath('/Admin/System/RuntimeConfig'); this.setMethod('GET') }
    async onRequest(req, res) {
        const { uuid, session } = req.query
        if (!uuid || !session) return res.json({ ...BaseStdResponse.MISSING_PARAMETER })
        if (!await checkAdmin(uuid, session)) return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED })
        return res.json({ ...BaseStdResponse.OK, data: await getAllRuntimeConfigs() })
    }
}

class SaveRuntimeConfig extends API {
    constructor() { super(); this.setPath('/Admin/System/RuntimeConfig'); this.setMethod('PUT') }
    async onRequest(req, res) {
        const { uuid, session, config } = req.body
        if (!uuid || !session || !config || typeof config !== 'object') return res.json({ ...BaseStdResponse.MISSING_PARAMETER })
        if (!await checkAdmin(uuid, session)) return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED })
        try {
            if (!CONFIG_KEYS.includes(config.key)) return res.json({ ...BaseStdResponse.ERR, msg: `不支持的配置项：${config.key}` })
            await saveRuntimeConfig({ ...config, updatedBy: uuid })
            return res.json({ ...BaseStdResponse.OK })
        } catch (error) {
            return res.json({ ...BaseStdResponse.ERR, msg: error.message || '保存配置失败' })
        }
    }
}

class SelectRuntimeConfig extends API {
    constructor() { super(); this.setPath('/Admin/System/RuntimeConfig/Select'); this.setMethod('PUT') }
    async onRequest(req, res) {
        const { uuid, session, key, name } = req.body
        if (!uuid || !session || !key || !name) return res.json({ ...BaseStdResponse.MISSING_PARAMETER })
        if (!await checkAdmin(uuid, session)) return res.status(401).json({ ...BaseStdResponse.ACCESS_DENIED })
        try { await selectRuntimeConfig({ key, name, updatedBy: uuid }); return res.json({ ...BaseStdResponse.OK }) }
        catch (error) { return res.json({ ...BaseStdResponse.ERR, msg: error.message || '切换配置失败' }) }
    }
}

module.exports = { GetRuntimeConfig, SaveRuntimeConfig, SelectRuntimeConfig }
