import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { NotificationTemplateProvider } from '#providers/NotificationTemplateProvider';
import { Req, Res } from '#interfaces/IApi';
import { queryModifier } from '#middlewares/query-modifier';
import verify, { requireAdmin } from '#middlewares/auth';
import { validateId, validateZod } from '#middlewares/validators';
import { NotificationTemplateUpdateBodySchema } from '#contracts/notification-template/schema';
import { Errors } from '#interfaces/error';
import { sendSuccess } from '#utils/responseUtils';
import { AuditLogService } from '#services/audit/auditLogService';

export default (_express: Application) => {
	const provider = new NotificationTemplateProvider();

	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await provider.getById({ id: req.params.id! });
					if (!data) throw Errors.notFound('NotificationTemplate');
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		put: {
			middleware: [verify, requireAdmin, validateId, validateZod(NotificationTemplateUpdateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await provider.put(req.params.id!, {
						...req.body,
						updated_at: new Date(),
						updated_by: req.user?.id ?? null,
					});

					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'NotificationTemplate',
						entityId: data.id,
						changeType: 'UPDATE',
						payload: {
							before: null,
							after: data.toJSON(),
							changed_fields: Object.keys(req.body),
						},
						reason: `Updated notification template: ${data.code}`,
					});

					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		delete: {
			middleware: [verify, requireAdmin, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const template = await provider.getById({ id: req.params.id! });
					if (!template) throw Errors.notFound('NotificationTemplate');

					await provider.delete(req.params.id!, { force: true });

					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'NotificationTemplate',
						entityId: req.params.id!,
						changeType: 'DELETE',
						payload: {
							before: template.toJSON(),
							after: null,
							changed_fields: Object.keys(template.toJSON()),
						},
						reason: `Deleted notification template: ${template.code}`,
					});

					return sendSuccess(res, { message: 'Notification template deleted successfully' });
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
