const { ManagementClient } = require('authing-node-sdk')
const managementClient  = new ManagementClient({
    accessKeyId: '6686bffb373d06911e24a969',
    accessKeySecret: "4e978331675938d1bc81fb109e67d59a",
    host: 'https://textbook.u2-dev.hep.com.cn', // 应用的认证地址
})

export function defineUserAfterSave(){
    Parse.Cloud.afterSave("_User", async (request) => {
        // console.log("save _User",request?.object?.id)
        let query = new Parse.Query("Profile");
        query.equalTo("user",request?.object?.id)
        let profile = await query.first();
       syncUserProfileToAuthing(request?.object,profile)
    });

    Parse.Cloud.afterSave("Profile", async (request) => {
        // console.log("save Profile",request?.object?.id)
        let query = new Parse.Query("Profile");
        query.include("user");
        profile = await query.get(request?.object?.id);
        syncUserProfileToAuthing(profile.get("user"),profile)
     
    });
}


async function syncUserProfileToAuthing(user,profile){
    if(!user?.id) return
    let userInfo = user.toJSON();
    userInfo = fixJsonFileds(userInfo)
    if(profile?.id){
        let pjson = profile.toJSON();
        delete pjson.objectId;
        pjson= fixJsonFileds(pjson)
        Object.keys(pjson).forEach(key=>{
            userInfo[key] = pjson[key]
        })
    }
    // 映射对应字段
    userInfo.company = userInfo.companyName
    delete userInfo.companyName
    userInfo.userType = userInfo.identity
    delete userInfo.identity
    userInfo.userId = userInfo.objectId
    delete userInfo.objectId
    userInfo.identifyStatus = userInfo.accountState
    // 自定义数据全量同步
    userInfo.customData = JSON.parse(JSON.stringify(userInfo))
    // {
    //     identifyStatus : userInfo.accountState
    // }

    // console.log(userInfo)
    // 同步数据至Authing用户池
    let result
    try{
        result = await managementClient.updateUser(userInfo)
        // console.log(result)
    }catch(err){console.log(err)}

}

function fixJsonFileds(json){
    // Parse独有关系数据
    delete json.ACL
    delete json.className
    delete json.sessionToken
    delete json.company
    delete json.user
    delete json.createdAt
    delete json.updatedAt
    // 来自Authing的数据
    delete json?.loginsCount
    delete json?.lastIP
    delete json?.lastLogin
    return json
}