import { Schema, model, Document, Types } from 'mongoose'
import constants from '../../utils/constants'

const SmartMatchUserDataSchema = new Schema({
	user: {
		type: Types.ObjectId,
		ref: 'User',
		required: true,
	},
	response: {
		type: String,
		enum: ['yes', 'no']
	},
	responseAt: Date,
	feedback: {
		type: String,
		enum: ['good', 'ok', 'bad']
	},
	feedbackAt: Date
}, {versionKey: false, _id: false})

interface ISmartMatchUserData {
	user: Types.ObjectId
	response?: 'yes' | 'no'
	responseAt?: Date
	feedback?: 'good' | 'ok' | 'bad'
	feedbackAt?: Date
}

const SmartMatchScoresSchema = new Schema({
	energy:   { type: Number, required: true },
	values:   { type: Number, required: true },
	activity: { type: Number, required: true },
	intent:   { type: Number, required: true },
}, { versionKey: false, _id: false })

interface ISmartMatchScores {
	energy: number
	values: number
	activity: number
	intent: number
}

const SmartMatchSchema = new Schema(
	{
		id: {
			// 'john_doe:amy_jackson', sorted lexicographically
			type: String,
			required: true
		},
		userA: {
			type: SmartMatchUserDataSchema,
			required: true,
		},
		userB: {
			type: SmartMatchUserDataSchema,
			required: true,
		},
		score: {
			type: Number,
			required: true
		},
		scores: {
			type: SmartMatchScoresSchema,
		},
		status: {
			type: String,
			enum: ['pending', 'accepted', 'declined', 'expired'],
			default: 'pending'
		},
		chat: {
			type: Types.ObjectId,
			ref: 'Chat'
		},
		community: {
			type: Types.ObjectId,
			ref: 'Community',
			required: true
		},
		suggested: Boolean,
		suggestedAt: Date,
		acceptedAt: Date,
		declinedAt: Date,
		expiredAt: {
			type: Date,
			default: () => {
				const now = new Date()
				now.setDate(now.getDate() + constants.defaultSmartMatchExpiryInDays)
			}
		},
		clickReason: String,
		sharedEnergy: String,
		activityIdea: String,
		conversationStarter: String,
	},
	{ versionKey: false, timestamps: true }
)

export interface ISmartMatch extends Document {
	_id: Types.ObjectId
	id: string     				// 'username1:username2'
	userA: ISmartMatchUserData
	userB: ISmartMatchUserData
	score: number
	scores?: ISmartMatchScores
	status: 'pending' | 'accepted' | 'declined' | 'expired'
	chat?: Types.ObjectId
	community: Types.ObjectId
	suggested?: boolean
	clickReason?: string
	sharedEnergy?: string
	activityIdea?: string
	conversationStarter?: string
	createdAt: Date
	updatedAt: Date
	expiredAt: Date
	suggestedAt?: Date
	acceptedAt?: Date
	declinedAt?: Date
}

export const SmartMatch = model<ISmartMatch>('SmartMatch', SmartMatchSchema, 'smart-matches')
