const { Notifications } = require('../../models');
const { formatCase } = require('../../util/formatter');

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

		const notifications = await Notifications.findAll({
			where: { member_id: memberId },
			order: [['createdAt', 'DESC']],
		});

		if (!notifications || notifications.length === 0) {
			return res.status(200).json({ message: 'No notifications found', notifications: [] });
		}

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

exports.readNotification = async (req, res, next) => {
	const { id } = req.params;

	try {
		const notification = await Notifications.findByPk(id);

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

		notification.is_read = true;
		await notification.save();

		res.status(200).json({
			success: true,
			message: 'Notification marked as read',
			notification: formatCase(notification),
		});
	} catch (error) {
		next(error);
	}
};
