const { AuthenticationClient } = require('authing-js-sdk')
const { pgClient } = require('../../db/pg-instance')

Parse.Cloud.define("authingLogin", async (request) => {
    let token = request.params.token;
    if(token) {
        let result = await syncSessionWithIdToken(token)
        return result
    }
    return null
  },{
    fields : {
        token:{
            required:true
        }
    }
  });
  

/**
 * 同步用户登录信息
 * @desc
 * https://docs.authing.cn/v2/reference/sdk-for-node/authentication/AuthenticationClient.html#获取当前登录的用户信息
 * @param {*} token 
 * @returns 
 */
async function syncSessionWithIdToken(token){
    // 通过用户的 id_token 初始化之后获取用户信息

    let authenticationClient = new AuthenticationClient({
        appId: '6682ab96b7bd5db59d6785a0',
        appHost: 'https://textbook.u2-dev.hep.com.cn', // 应用的认证地址
        token: token
    })

    let user = await authenticationClient.getCurrentUser()
    // console.log(user)

    // 生成Parse库所需_Session记录 objectId唯一
    let sessionObjectId = generateObjectId(user?.id+user?.token)
    let username = user?.phone || user?.username || user?.email
    let syncSessionSQL = `
    INSERT INTO "_User" ("objectId", "username","mobile", "createdAt", "updatedAt")
    VALUES
    ($2,$7,$8,$5,$6)
    ON conflict("objectId") DO UPDATE
    SET 
    "username" = excluded."username",
    "updatedAt"=excluded."updatedAt";


    INSERT INTO "_Session" ("objectId", "user", "sessionToken","expiresAt", "createdAt", "updatedAt")
    VALUES
    ($1, $2,$3,$4,$5,$6)
    ON conflict("objectId") DO UPDATE
    SET 
    "user" = excluded."user",
    "sessionToken" = excluded."sessionToken",
    "expiresAt"=excluded."expiresAt",
    "updatedAt"=excluded."updatedAt";
    `
    let params = [sessionObjectId,user?.id,user?.token,user?.expiresAt,new Date(),new Date(),username,user?.phone]
    if(user?.id&&user?.token){
        try {
            // 查询：数据库版本信息
            const data = await pgClient.any(syncSessionSQL,params);
            // console.log(data)
            return {
                sid:sessionObjectId,
                uid:user?.id,
                sessionToken:user?.token
            };
        } catch (error) {
            console.error('Error executing query:', error);
            return null;
        }
    }
}
module.exports.syncSessionWithIdToken = syncSessionWithIdToken

const crypto = require('crypto');
function generateObjectId(inputString) {
    const hash = crypto.createHash('sha256').update(inputString).digest('hex');
    const objectId = hash;
    return objectId;
}