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

export function defineAuthingLogin(){
    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
            }
        }
    });

    Parse.Cloud.define("userFind", async (request) => {
        let mobile = request.params.mobile;
        if(mobile) {
            let user = {
                mobile:mobile
            }
            let result = await getParseUserByAuthingUser(user);
            return result;
        }
        return null;
    },{
        fields : {
            mobile:{
                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?.username || user?.phone || user?.email
    let ParseExistUser = await getParseUserByAuthingUser(user);
    let userId = ParseExistUser?.objectId || user?.id;
    console.log("userId",userId);
    console.log("authingUser",user);
    console.log("ParseExistUser",ParseExistUser);
    let syncSessionSQL = `
    INSERT INTO "_User" (
        "objectId", "username","mobile","phone", "createdAt", "updatedAt",
        "lastIP","lastLogin","userSourceType","loginsCount"
        )
    VALUES
    (
        $2,$7,$8,$8,$5,$6,
        $9,$10,$11,$12
        )
    ON conflict("objectId") DO UPDATE
    SET 
    "username" = excluded."username",
    "updatedAt"=excluded."updatedAt",
    "mobile"=excluded."mobile",
    "phone"=excluded."phone",
    "lastIP"=excluded."lastIP",
    "lastLogin"=excluded."lastLogin",
    "userSourceType"=excluded."userSourceType",
    "loginsCount"=excluded."loginsCount";


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


async function getParseUserByAuthingUser(user){
    let sql = `
    SELECT * FROM "_User" WHERE
    "objectId"=$1 OR 
    "objectId"=$2 OR
    "username"=$3 OR 
    "username"=$4 OR 
    "username"=$5 OR 
    "username"=$6 OR 
    ("mobile" IS NOT NULL AND "mobile" = $4) OR 
    ("phone" IS NOT NULL AND "phone"  = $4) OR 
    ("mobile" IS NOT NULL AND "mobile" = $5) OR 
    ("phone"  IS NOT NULL AND "phone"  = $5) OR 
    ("email" IS NOT NULL AND "email" = $6)
    `
    let params = [
        user?.id, //1
        user?.externalId,//2
        user?.username,//3
        user?.phone,//4
        user?.mobile,//5
        user?.email//6
    ]
    let data = [] 
    try{
        data = await pgClient().any(sql,params);
        console.log("data same user:",data)
        if(data?.length){
            return data[0]
        }
    }catch(err){
        console.error(err)
    }
    return null

}

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