import axios from "axios";

export const enrollUserInCourse = async (
	courseid: number | string,
	userid: number | string,
) => {
	const { data: enrollmentResponse } = await axios.get(
		`${process.env.NEXT_PUBLIC_MOODLE_URL}/webservice/rest/server.php`,
		{
			params: {
				wstoken: process.env.MOODLE_TOKEN,
				wsfunction: "enrol_manual_enrol_users",
				moodlewsrestformat: "json",
				enrolments: [
					{
						roleid: 5,
						userid: typeof userid === "string" ? parseInt(userid) : userid,
						courseid:
							typeof courseid === "string" ? parseInt(courseid) : courseid,
					},
				],
			},
		},
	);
	if (enrollmentResponse !== null) console.error(enrollmentResponse);
	return enrollmentResponse;
};

export const getMoodleUserById = async (id: string) => {
	const { data: user } = await axios.get(
		`${process.env.NEXT_PUBLIC_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
	);
};
