const axios = require('axios')
const https = require('https')
const { getRuntimeConfig } = require('./RuntimeConfig')

const VALID_SOCIAL_TYPES = ['qq', 'wx']

function normalizeSocialType(type) {
    const socialType = type || 'qq'
    return VALID_SOCIAL_TYPES.includes(socialType) ? socialType : null
}

function getEnabledUniLoginTypes(uniConfig = {}) {
    if (!Array.isArray(uniConfig.enabledTypes)) return [...VALID_SOCIAL_TYPES]
    return uniConfig.enabledTypes
        .map(type => normalizeSocialType(type))
        .filter(Boolean)
        .filter((type, index, list) => list.indexOf(type) === index)
}

function isUniLoginTypeEnabled(uniConfig, type) {
    const socialType = normalizeSocialType(type)
    if (!socialType) return false
    return getEnabledUniLoginTypes(uniConfig).includes(socialType)
}

async function getUniLoginRuntimeConfig({ requireEnabledType } = {}) {
    const uniConfig = await getRuntimeConfig('unilogin', { required: false, defaultValue: null })
    if (!uniConfig || !uniConfig.url || !uniConfig.appid || !uniConfig.appkey) {
        throw new Error('聚合登录暂未配置')
    }
    if (requireEnabledType && !isUniLoginTypeEnabled(uniConfig, requireEnabledType)) {
        throw new Error('该登录方式已关闭')
    }
    return uniConfig
}

async function fetchUniLoginProfile(type, code) {
    const socialType = normalizeSocialType(type)
    if (!socialType)
        throw new Error('不支持的第三方登录类型')

    const uniConfig = await getUniLoginRuntimeConfig({ requireEnabledType: socialType })
    const url = `${uniConfig.url}/connect.php?act=callback&appid=${uniConfig.appid}&appkey=${uniConfig.appkey}&type=${socialType}&code=${code}`

    const r = await axios.get(url, {
        httpsAgent: new https.Agent({
            rejectUnauthorized: false
        }),
        proxy: false
    })

    if (!r || r.data?.code !== 0)
        throw new Error(r.data?.msg || 'api接口错误')

    return {
        ...r.data,
        social_type: socialType
    }
}

module.exports = {
    VALID_SOCIAL_TYPES,
    getEnabledUniLoginTypes,
    getUniLoginRuntimeConfig,
    isUniLoginTypeEnabled,
    normalizeSocialType,
    fetchUniLoginProfile
}
