import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { ResidentProvider } from '#providers/ResidentProvider';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { validateId } from '#middlewares/validators';
import { Errors } from '#interfaces/error';
import { sendSuccess } from '#utils/responseUtils';
import { z } from 'zod';
import type { RoommateListDataSchema } from '#contracts/resident/schema';

export default (_express: Application) => {
	const residentProvider = new ResidentProvider();
	return <Resource>{
		get: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					// Check if resident exists
					const resident = await residentProvider.getById({ id: req.params.id! });
					if (!resident) throw Errors.notFound('Resident');

					const data = await residentProvider.getRoommates({ id: req.params.id! });
					const responseData = {
						count: data.count,
						rows: data.rows as z.infer<typeof RoommateListDataSchema>['rows'],
					};
					return sendSuccess(res, responseData);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
