const { Concerns, ConcernMessages, Members, sequelize } = require('../../models');
const { formatCase } = require('../../util/formatter');

exports.sendConcern = async (req, res, next) => {
	const transaction = await sequelize.transaction();

	try {
		const { concern_id, type, message } = req.body;
		const { memberId: member_id } = req;

		if (!message) {
			await transaction.rollback();
			return res.status(400).json({
				success: false,
				message: 'Message is required',
			});
		}

		let concernId = concern_id;
		let isNewConcern = false;

		if (!concern_id) {
			if (!type) {
				await transaction.rollback();
				return res.status(400).json({
					success: false,
					message: 'Type is required when no concern_id is provided',
				});
			}

			let concern = await Concerns.findOne({
				where: { type, member_id },
				transaction,
			});

			if (!concern) {
				concern = await Concerns.create(
					{
						type,
						member_id,
						createdAt: new Date(),
					},
					{ transaction },
				);
				isNewConcern = true;
			}
			concernId = concern.id;
			if (concern.is_resolved) {
				await concern.update({ is_resolved: false }, { transaction });
			}
		} else {
			const existingConcern = await Concerns.findByPk(concern_id, { transaction });
			if (!existingConcern) {
				await transaction.rollback();
				return res.status(404).json({
					success: false,
					message: 'Concern not found',
				});
			}
			concernId = existingConcern.id;
			if (existingConcern.is_resolved) {
				await existingConcern.update({ is_resolved: false }, { transaction });
			}
		}

		await ConcernMessages.create(
			{
				concernId,
				message,
				member_id,
				from_member: true,
				createdAt: new Date(),
			},
			{ transaction },
		);

		await transaction.commit();

		return res.status(201).json({
			success: true,
			message: isNewConcern ? 'New concern created and message sent successfully' : 'Message sent successfully',
			data: {
				concern_id: concernId,
			},
		});
	} catch (error) {
		await transaction.rollback();
		next(error);
	}
};

exports.getMemberConcerns = async (req, res, next) => {
	try {
		const { memberId: member_id } = req;

		const concerns = await Concerns.findAll({
			where: {
				member_id,
			},
			include: [
				{
					model: ConcernMessages,
					as: 'messages',
					where: { member_id },
					attributes: ['id', 'message', 'from_member', 'createdAt'],
					order: [['createdAt', 'ASC']],
				},
			],
			order: [['createdAt', 'DESC']],
		});

		return res.status(200).json({
			success: true,
			data: formatCase(concerns),
		});
	} catch (error) {
		next(error);
	}
};

exports.getConcernDetails = async (req, res, next) => {
	try {
		const { type } = req.params;
		const { memberId: member_id } = req;

		const concern = await Concerns.findOne({
			where: {
				type,
				member_id,
			},
			include: [
				{
					model: ConcernMessages,
					as: 'messages',
					attributes: ['id', 'message', 'member_id', 'from_member', 'createdAt'],
					include: [
						{
							model: Members,
							as: 'member',
							attributes: ['id', 'first_name', 'last_name'],
						},
					],
					order: [['createdAt', 'ASC']],
				},
			],
		});

		if (!concern) {
			return res.status(404).json({
				success: false,
				message: 'Concern not found',
			});
		}

		return res.status(200).json({
			success: true,
			data: formatCase(concern),
		});
	} catch (error) {
		next(error);
	}
};
