import axios from "axios";

export const getMoodleUserById = async (id: string) => {
	const { data: user } = await axios.get(
		`${process.env.MOODLE_URL}/webservice/rest/server.php`,
		{
			params: {
				wstoken: process.env.MOODLE_TOKEN,
				wsfunction: "core_user_get_users_by_field",
				moodlewsrestformat: "json",
				field: "idnumber",
				values: [id],
			},
			paramsSerializer: {
				indexes: true, // use brackets with indexes
			},
		},
	);
	const u = user[0];
	return (
		(u as {
			id: number;
			username: string;
			firstname: string;
			lastname: string;
			fullname: string;
			email: string;
		}) || null
	);
};

export const getMoodleQuizResult = async (userId: string, quizId: string) => {
	const { data: quizzes } = await axios.get(
		`${process.env.MOODLE_URL}/webservice/rest/server.php`,
		{
			params: {
				wstoken: process.env.MOODLE_TOKEN,
				wsfunction: "mod_quiz_get_user_attempts",
				moodlewsrestformat: "json",
				quizid: quizId,
				userid: userId,
			},
		},
	);
	return quizzes;
};

export const getMoodleCourseCompletionStatus = async (
	userId: string,
	courseId: string,
) => {
	const { data: completionStatus } = await axios.get(
		`${process.env.MOODLE_URL}/webservice/rest/server.php`,
		{
			params: {
				wstoken: process.env.MOODLE_TOKEN,
				wsfunction: "core_completion_get_course_completion_status",
				moodlewsrestformat: "json",
				userid: userId,
				courseid: courseId,
			},
		},
	);
	return completionStatus as {
		completionstatus: {
			completed: true;
			aggregation: number;
		};
		warnings: [];
	};
};
