import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { DebtReminderPolicyProvider } from '#providers/DebtReminderPolicyProvider';
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 { DebtReminderPolicyCreateBodySchema } from '#contracts/debt-reminder-policy/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';

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

	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await provider.getAllOptimized(req.payload || {});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},

		post: {
			middleware: [verify, requireAdmin, validateZod(DebtReminderPolicyCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const { name, reminderType, daysOffset, sendTime, channels, status, targets } = req.body;

					const data = await provider.createWithTargets({
						name,
						reminder_type: reminderType,
						days_offset: daysOffset,
						send_time: sendTime,
						channels,
						status: status ?? 'ACTIVE',
						targets,
						created_by: req.user?.id ?? null,
					});

					const detail = await provider.getByIdOptimized(data.id);
					return sendSuccess(res, detail);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
