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

const RequestSchema = new Schema({
	method: String,
	path: String,
	body: Schema.Types.Mixed,
	headers: Schema.Types.Mixed
}, { versionKey: false, _id: false })

const ResponseSchema = new Schema({
	status: Number,
	body: Schema.Types.Mixed,
	headers: Schema.Types.Mixed,
	locals: Schema.Types.Mixed
}, { versionKey: false, _id: false })

const ErrorLogSchema = new Schema(
	{
		user: {
			type: Types.ObjectId,
			ref: 'User'
		},
		stacktrace: {
			type: String,
			required: true
		},
		request: RequestSchema,
		response: ResponseSchema,
		at: {
			type: Date,
			default: Date.now
		}
	},
	{ versionKey: false }
)

export interface IErrorLog extends Document {
	_id: Types.ObjectId
	user?: Types.ObjectId
	stacktrace: string
	request?: {
		method?: string
		path?: string
		body?: any
		headers?: Record<string, any>
	}
	response?: {
		status?: number
		body?: any
		headers?: Record<string, any>
		locals?: Record<string, any>
	}
	at: Date
}

export const ErrorLog = model<IErrorLog>('ErrorLog', ErrorLogSchema, 'error-logs')
