import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import { AuthService } from '#services/auth';
import { createRateLimit } from '#middlewares/auth';
import { validateZod } from '#middlewares/validators';
import { RegisterBodySchema } from '#contracts/auth/schema';
import { sendSuccess } from '#utils/responseUtils';
import type { RegisterResponseData } from '#contracts/auth/schema';
import { GenericError } from '#interfaces/error/generic';
import Config from '#config';

export default (_express: Application) => {
	return <Resource>{
		post: {
			middleware: [createRateLimit(15 * 60 * 1000, 5), validateZod(RegisterBodySchema)] as any, // Rate limit: 5 requests per 15 minutes
			handler: async (req: Req, res: Res) => {
				if (!Config.auth.enableRegister) {
					return res.error(new GenericError('FORBIDDEN'));
				}
				try {
					const user = await AuthService.register(req.body);
					const responseData = {
						id: user.id as string,
						email: user.email,
						username: user.username ?? null,
						status: user.status as string,
					} satisfies RegisterResponseData;
					return sendSuccess(res, responseData);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
