import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { ResidentProvider } from '#providers/ResidentProvider';
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 { ResidentCreateBodySchema } from '#contracts/resident/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';
import { AuditLogService } from '#services/audit/auditLogService';

export default (_express: Application) => {
	const residentProvider = new ResidentProvider();
	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await residentProvider.getAllWithResidence(req.payload || {});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, requireAdmin, validateZod(ResidentCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await residentProvider.createWithResidence({
						...req.body,
						created_by: req.user?.id || null,
						updated_by: req.user?.id || null,
					});

					// Audit log for resident creation
					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'Resident',
						entityId: data.id,
						changeType: 'CREATE',
						payload: {
							before: null,
							after: data.toJSON(),
							changed_fields: Object.keys(req.body),
						},
						reason: `Created new resident: ${req.body.full_name || 'N/A'}`,
					});

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