import { addDays } from 'date-fns'; import { type Model, type Document, Schema } from 'mongoose'; import { getOrCreateModel } from '~/server/util/mongoose-utils'; import { type IThreadRelation, ThreadType } from '../../interfaces/thread-relation'; const DAYS_UNTIL_EXPIRATION = 3; const generateExpirationDate = (): Date => { return addDays(new Date(), DAYS_UNTIL_EXPIRATION); }; export interface ThreadRelationDocument extends IThreadRelation, Document { updateThreadExpiration(): Promise; } interface ThreadRelationModel extends Model { getExpiredThreadRelations(limit?: number): Promise; } const schema = new Schema({ userId: { type: Schema.Types.ObjectId, ref: 'User', required: true, }, aiAssistant: { type: Schema.Types.ObjectId, ref: 'AiAssistant', }, threadId: { type: String, required: true, unique: true, }, title: { type: String, }, type: { type: String, enum: Object.values(ThreadType), required: true, }, expiredAt: { type: Date, default: generateExpirationDate, required: true, }, }); schema.statics.getExpiredThreadRelations = async function(limit?: number): Promise { const currentDate = new Date(); const expiredThreadRelations = await this.find({ expiredAt: { $lte: currentDate } }).limit(limit ?? 100).exec(); return expiredThreadRelations; }; schema.methods.updateThreadExpiration = async function(): Promise { this.expiredAt = generateExpirationDate(); await this.save(); }; export default getOrCreateModel('ThreadRelation', schema);