import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { DebtReminderPolicyProvider } from '#providers/DebtReminderPolicyProvider';
import { Req, Res } from '#interfaces/IApi';
import verify, { requireAdmin } from '#middlewares/auth';
import { validateId, validateZod } from '#middlewares/validators';
import { DebtReminderPolicyUpdateBodySchema } from '#contracts/debt-reminder-policy/schema';
import { Errors } from '#interfaces/error';
import { sendSuccess } from '#utils/responseUtils';

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

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

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

					const updated = await provider.updateWithTargets(req.params.id!, {
						...(name !== undefined && { name }),
						...(reminderType !== undefined && { reminder_type: reminderType }),
						...(daysOffset !== undefined && { days_offset: daysOffset }),
						...(sendTime !== undefined && { send_time: sendTime }),
						...(channels !== undefined && { channels }),
						...(status !== undefined && { status }),
						...(targets !== undefined && { targets }),
						updated_by: req.user?.id ?? null,
					});

					if (!updated) throw Errors.notFound('DebtReminderPolicy');

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

		delete: {
			middleware: [verify, requireAdmin, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const policy = await provider.getByIdOptimized(req.params.id!);
					if (!policy) throw Errors.notFound('DebtReminderPolicy');

					await provider.hardDelete(req.params.id!);

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