import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { UserProvider } from '#providers/UserProvider';
import { AuthService } from '#services/auth';
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 { UserCreateBodySchema } from '#contracts/user/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';

export default (_express: Application) => {
	const userProvider = new UserProvider();
	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await userProvider.getAll(req.payload || {});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, requireAdmin, validateZod(UserCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const { email, password, username, first_name, last_name, phone, role } = req.body;
					const data = await AuthService.register({ email, password, username, first_name, last_name, phone, role });
					return sendSuccess(res, data.toJSON());
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
