/**
 * 张江小助手
 * 没有权限 2023-02-06 确定此需求
 */

import {Schema} from 'mongoose';
import { baseDB } from '../../db/mongo/dbInit';

const chartSchema = new Schema({
    userId:{type:String, index:true},//用户标识 唯一
    conversationId:String,//会话id
    conversationMs:Number,//最近一次会话时间
    chatId:String,//对话id
    additionalMessages:String,//对话上下文json格式，数组限制长度为10
});

var chartModel;
export function initModel(){
    chartModel = baseDB.model('chart', chartSchema);
    chartModel.selectOnceData = async function (paramater:object) {
        let selectInfo = await chartModel.findOne(paramater).exec();
        if (selectInfo) {
            if (!selectInfo.runSave) {
                selectInfo.runSave = selectInfo.save;
                selectInfo.save = save.bind(selectInfo)
            }
        }
        return selectInfo;
    }
}
export async function save(throwError=false) {
    if (!this.isModified()) return;
    await this.runSave({validateBeforeSave:false}).catch(err=>{
        console.log(err);
    });
}


export async function selectChatInfo(userId:string) {
    return await chartModel.selectOnceData({userId});
}


export async function createChatInfo(userId:string) {
    let initInfo = {
        userId, 
        conversationId:'', 
        conversationMs:0, 
        chatId:'', 
        additionalMessages:'[]'
    }
    return await chartModel.create(initInfo);
}
