import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import verify, { requireAdmin } from '#middlewares/auth';
import { validateId } from '#middlewares/validators';
import { GenericError as _GenericError } from '#interfaces/error/generic';
import { sendSuccess } from '#utils/responseUtils';
import { PasswordService } from '#services/auth/passwordService';

export default (_express: Application) => {
	return <Resource>{
		put: {
			middleware: [verify, requireAdmin, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const userId = String(req.params.id);

					// Reset password to DEFAULT_PASSWORD from environment
					await PasswordService.resetPasswordToDefault(userId, req.user?.id);

					return sendSuccess(
						res,
						{ success: true },
						'Password reset successfully. User must change password on next login.',
						'Password reset successfully. User must change password on next login.',
					);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
