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 { validateZod, validateQueryZod } from '#middlewares/validators';
import { NotificationTemplateCreateBodySchema } from '#contracts/notification-template/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';
import { AuditLogService } from '#services/audit/auditLogService';
import { generateTemplateCode } from '#utils/templateCodeGenerator';
import { Errors } from '#interfaces/error';

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

	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await provider.getAll(req.payload || {});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, requireAdmin, validateZod(NotificationTemplateCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					// Tự sinh code MTB-01, MTB-02, ... nếu không truyền
					const code =
						req.body.code ??
						(await generateTemplateCode());

					// Kiểm tra code đã tồn tại chưa (khi user tự nhập)
					if (req.body.code) {
						const existing = await provider.getOne({ where: { code } });
						if (existing) throw Errors.conflict('Notification template code already exists');
					}

					const data = await provider.create({
						...req.body,
						code,
						created_by: req.user?.id ?? null,
					});

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

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