import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType, modelOptions, ReturnModelType, mongoose } from '@typegoose/typegoose';
import { UpdateChannelParam } from '../domain/backEndField/params';
import { genCode } from '../pubUtils/util';

/**
  * 私聊信息
**/
@modelOptions({ schemaOptions: { id: false } })
@index({ roomId: 1, seqId: -1 })
@index({ msgId: 1 })
export default class ChannelInfo extends BaseModel {

    @prop({ required: true })
    code: string;              // 渠道标识

    @prop({ required: true })
    platform: string;              // 渠道标识
    
    @prop({ required: true })
    desc: string;                   // 渠道描述

    @prop({ required: true })
    isDefaultPolicy: boolean;        // 是否使用默认协议

    @prop({ required: true })
    userPolicyLink: string;        // 用户协议

    @prop({ required: true })
    privacyPolicyLink: string;      // 隐私协议

    public static async findAll() {
      const result: ChannelInfoType[] = await ChannelInfoModel.find({}).select({ _id: false }).lean();
      return result
    }

    public static async findByPlatform(platform: string) {
      const result: ChannelInfoType = await ChannelInfoModel.findOne({ platform }).lean();
      return result
    }

    public static async updateChannel(code: string, values: UpdateChannelParam) {
      if(code == 'new') {
        code = genCode(6);
      }
      delete values.code;
      const result: ChannelInfoType = await ChannelInfoModel.findOneAndUpdate({ code }, values, { new: true, upsert: true }).lean();
      return result
    }
}

export let ChannelInfoModel: ReturnModelType<typeof ChannelInfo, {}>;
export function loadChannelInfo(connect: mongoose.Connection) {
  ChannelInfoModel = getModelForClass(ChannelInfo, {
        existingConnection: connect
    });
}
export interface ChannelInfoType extends Pick<DocumentType<ChannelInfo>, keyof ChannelInfo> {};
export type ChannelInfoParam = Partial<ChannelInfoType>;

