import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Op } from 'sequelize';
import { Req, Res } from '#interfaces/IApi';
import { queryModifier } from '#middlewares/query-modifier';
import verify from '#middlewares/auth';
import { NotificationReceiptProvider } from '#providers/NotificationReceiptProvider';
import { validateQueryZod } from '#middlewares/validators';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';

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

	return <Resource>{
		put: {
			middleware: [verify, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const filter = req.payload?.filters || {};
					const where = {
						[Op.and]: [
							filter,
							{
								user_id: req.user?.id,
								read_at: null,
								deleted_at: null,
							},
						],
					};

					const data = await notificationReceiptProvider.bulkUpdate(
						where as any,
						{
							read_at: new Date(),
							updated_at: new Date(),
						} as any,
					);

					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
