const { Conversations, ConversationMembers, Messages, MessageAttachments } = require('../models');

const ensureConversationExists = async (userId, receiverId, convoId) => {
	const existingConvo = await Conversations.findOne({
		where: { id: convoId },
		include: [
			{
				model: ConversationMembers,
				where: { user_id: userId },
				as: 'members',
				required: true,
			},
			{
				model: ConversationMembers,
				where: { user_id: receiverId },
				as: 'members',
				required: true,
			},
		],
	});

	if (existingConvo) {
		return existingConvo.id;
	} else {
		throw new Error('Conversation does not exist or the user is not part of it.');
	}
};

const findOrCreateConversation = async (userId, receiverId) => {
	const userConversations = await ConversationMembers.findAll({
		where: { user_id: userId },
		attributes: ['convo_id'],
	});

	const receiverConversations = await ConversationMembers.findAll({
		where: { user_id: receiverId },
		attributes: ['convo_id'],
	});

	const userConvoIds = userConversations.map((member) => member.convo_id);
	const receiverConvoIds = receiverConversations.map((member) => member.convo_id);
	const commonConvoIds = userConvoIds.filter((convoId) => receiverConvoIds.includes(convoId));

	if (commonConvoIds.length > 0) {
		return commonConvoIds[0];
	} else {
		return await createNewConversation(userId, receiverId);
	}
};

const createNewConversation = async (userId, receiverId) => {
	try {
		const newConvo = await Conversations.create({
			convo_type: 'Private',
			status: 'Active',
		});

		await Promise.all([
			ConversationMembers.create({
				convo_id: newConvo.id,
				user_id: userId,
			}),
			ConversationMembers.create({
				convo_id: newConvo.id,
				user_id: receiverId,
			}),
		]);

		return newConvo.id;
	} catch (err) {
		throw new Error('Error creating new conversation: ' + err.message);
	}
};

const saveMessage = async (convoId, senderId, content, attachments) => {
	const message = await Messages.create({
		convo_id: convoId,
		sender_id: senderId,
		content,
		is_seen: false,
	});

	if (attachments && attachments.length > 0) {
		const attachmentRecords = attachments.map((file) => ({
			message_id: message.id,
			image: file.filename,
		}));

		await MessageAttachments.bulkCreate(attachmentRecords);
	}

	return message.id;
};

module.exports = {
	ensureConversationExists,
	saveMessage,
	findOrCreateConversation,
};
