import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { validateId } from '#middlewares/validators';
import { NotificationMessageProvider } from '#providers/NotificationMessageProvider';
import { NotificationReceiptProvider } from '#providers/NotificationReceiptProvider';
import { Errors } from '#interfaces/error';
import { assertNotificationOwnership } from '#services/notification/helpers/ownershipHelper';
import { sendSuccess } from '#utils/responseUtils';

export default (_express: Application) => {
	const notificationMessageProvider = NotificationMessageProvider.getInstance();
	const notificationReceiptProviderInstance = NotificationReceiptProvider.getInstance();

	return <Resource>{
		get: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const userId = req.user?.id as string;
					// Q-02: assertNotificationOwnership throws 404/403 on not found or ownership mismatch
					const notification = await assertNotificationOwnership(
						notificationMessageProvider,
						notificationReceiptProviderInstance,
						req.params.id!,
						userId,
					);

					return sendSuccess(res, notification.toJSON());
				} catch (error) {
					return res.error(error);
				}
			},
		},
		delete: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const userId = req.user?.id as string;
					const notificationId = req.params.id!;

					// Q-02: assertNotificationOwnership throws 404/403 if not found or not owned
					await assertNotificationOwnership(
						notificationMessageProvider,
						notificationReceiptProviderInstance,
						notificationId,
						userId,
					);

					// Soft delete notification
					const success = await notificationMessageProvider.delete(notificationId);
					if (!success) {
						throw Errors.notFound('Thông báo');
					}

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