import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { exportResidentsToXlsx } from '#services/residentExcelService';
import { Req, Res } from '#interfaces/IApi';
import verify, { requireAdmin } from '#middlewares/auth';
import { queryModifier } from '#middlewares/query-modifier';
import { validateQueryZod } from '#middlewares/validators';
import { SoftDeleteQueryParamsSchema } from '#contracts/shared';

export default (_express: Application) => {
	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(SoftDeleteQueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const buf = await exportResidentsToXlsx(req.payload || {});
					res.setHeader('Content-Disposition', `attachment; filename="residents-${Date.now()}.xlsx"`);
					res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
					return res.send(buf);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
