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

exports.getAllConcerns = async (req, res, next) => {
	try {
		const { page = 1, limit = 20, type, is_resolved } = req.query;
		const offset = (page - 1) * limit;

		const whereClause = {};
		if (type) whereClause.type = type;
		if (is_resolved !== undefined) whereClause.is_resolved = is_resolved === 'true';

		const concerns = await Concerns.findAndCountAll({
			where: whereClause,
			include: [
				{
					model: ConcernMessages,
					as: 'messages',
					attributes: ['id', 'message', 'member_id', 'from_member', 'createdAt'],
					include: [
						{
							model: Members,
							as: 'member',
							attributes: ['id', 'first_name', 'last_name', 'email_address'],
						},
					],
					order: [['createdAt', 'ASC']],
				},
			],
			order: [['createdAt', 'DESC']],
			limit: parseInt(limit),
			offset,
			distinct: true,
		});

		return res.status(200).json({
			success: true,
			message: 'Concerns retrieved successfully',
			data: {
				concerns: concerns.rows,
				pagination: {
					current_page: parseInt(page),
					total_pages: Math.ceil(concerns.count / limit),
					total_items: concerns.count,
					items_per_page: parseInt(limit),
				},
			},
		});
	} catch (error) {
		return next(error);
	}
};

exports.replyToConcern = async (req, res, next) => {
	try {
		const { concern_id } = req.params;
		const { message } = req.body;

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

		// Verify the concern exists
		const concern = await Concerns.findByPk(concern_id);
		if (!concern) {
			return res.status(404).json({
				success: false,
				message: 'Concern not found',
			});
		}

		// Create admin reply message
		await ConcernMessages.create({
			concernId: concern_id,
			message,
			member_id: null, // Admin messages don't have member_id
			from_member: false,
			createdAt: new Date(),
		});

		return res.status(201).json({
			success: true,
			message: 'Reply sent successfully',
		});
	} catch (error) {
		return next(error);
	}
};

exports.updateConcernStatus = async (req, res, next) => {
	try {
		const { concern_id } = req.params;
		const { is_resolved } = req.body;

		if (typeof is_resolved !== 'boolean') {
			return res.status(400).json({
				success: false,
				message: 'is_resolved must be a boolean value',
			});
		}

		const concern = await Concerns.findByPk(concern_id);
		if (!concern) {
			return res.status(404).json({
				success: false,
				message: 'Concern not found',
			});
		}

		await concern.update({ is_resolved });

		return res.status(200).json({
			success: true,
			message: `Concern marked as ${is_resolved ? 'resolved' : 'unresolved'}`,
			data: {
				concern_id: concern.id,
				is_resolved: concern.is_resolved,
			},
		});
	} catch (error) {
		return next(error);
	}
};

exports.getConcernDetails = async (req, res, next) => {
	try {
		const { concern_id } = req.params;

		const concern = await Concerns.findByPk(concern_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', 'email_address'],
						},
					],
					order: [['createdAt', 'ASC']],
				},
			],
		});

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

		return res.status(200).json({
			success: true,
			message: 'Concern details retrieved successfully',
			data: concern,
		});
	} catch (error) {
		return next(error);
	}
};
