import { Schema, model, Document, Types } from 'mongoose'

/** Snapshot of status and connection when a connection is accepted (for join statistics after status/connection expire). */
const ConnectionHistorySchema = new Schema(
	{
		from: {
			type: Types.ObjectId,
			ref: 'User',
			required: true,
		},
		to: {
			type: Types.ObjectId,
			ref: 'User',
			required: true,
		},
		acceptedAt: {
			type: Date,
			required: true,
		},
		statusSnapshot: {
			type: Schema.Types.Mixed,
			required: true,
		},
		connectionSnapshot: {
			type: Schema.Types.Mixed,
			required: true,
		},
		community: {
			type: Types.ObjectId,
			ref: 'Community'
		},
	},
	{ versionKey: false }
)

ConnectionHistorySchema.index({ acceptedAt: 1 })
ConnectionHistorySchema.index({ to: 1, acceptedAt: 1 })

export interface IConnectionHistory extends Document {
	_id: Types.ObjectId
	from: Types.ObjectId
	to: Types.ObjectId
	acceptedAt: Date
	statusSnapshot: Record<string, any>
	connectionSnapshot: Record<string, any>
	community?: Types.ObjectId
}

export const ConnectionHistory = model('ConnectionHistory', ConnectionHistorySchema, 'connection-histories')
