import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { NotificationReceiptProvider } from '#providers/NotificationReceiptProvider';
import { sendSuccess } from '#utils/responseUtils';

export default (_express: Application) => {
	const notificationReceiptProvider = NotificationReceiptProvider.getInstance();

	return <Resource>{
		get: {
			middleware: [verify],
			handler: async (req: Req, res: Res) => {
				try {
					const userId = req.user?.id as string;
					const unreadCountResult = await notificationReceiptProvider.getAll({
						where: {
							user_id: userId,
							read_at: null,
							deleted_at: null,
						},
						attributes: ['id'],
					});

					const unreadCount = unreadCountResult.count;
					const hasUnread = unreadCount > 0;

					return sendSuccess(res, {
						unread_count: unreadCount,
						has_unread: hasUnread,
					});
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
