// Task Team — Moodle API Connector — 2026-03-29
// Sync study goals and tasks with Moodle LMS

const MOODLE_URL = process.env.MOODLE_URL || "https://study.lubavitch.pro";

async function moodleCall(url, token, fn, params = {}) {
    const qs = new URLSearchParams({ wstoken: token, wsfunction: fn, moodlewsrestformat: "json", ...params });
    const res = await fetch(`${url}/webservice/rest/server.php?${qs}`);
    return res.json();
}

async function moodleConnector(app) {

    // Test connection
    app.get("/connectors/moodle/test", async (req) => {
        const { url, token } = req.query;
        try {
            const info = await moodleCall(url || MOODLE_URL, token, "core_webservice_get_site_info");
            return { status: "ok", site: info.sitename, user: info.fullname, version: info.release };
        } catch (e) {
            return { status: "error", message: e.message };
        }
    });

    // Import courses as goals
    app.post("/connectors/moodle/sync/courses", async (req) => {
        const { url, token, user_id } = req.body;
        const courses = await moodleCall(url || MOODLE_URL, token, "core_enrol_get_users_courses", { userid: user_id || "2" });
        
        let imported = 0;
        for (const c of courses) {
            await app.db.query(
                `INSERT INTO goals (title, target_date, plan, created_at)
                 VALUES ($1, $2, $3, NOW())
                 ON CONFLICT DO NOTHING`,
                [c.fullname, c.enddate ? new Date(c.enddate * 1000).toISOString() : null,
                 JSON.stringify({ moodle_course_id: c.id, shortname: c.shortname, progress: c.progress || 0 })]
            );
            imported++;
        }
        return { status: "ok", imported, total: courses.length };
    });

    // Import assignments as tasks
    app.post("/connectors/moodle/sync/assignments", async (req) => {
        const { url, token, course_id } = req.body;
        const data = await moodleCall(url || MOODLE_URL, token, "mod_assign_get_assignments", 
            course_id ? { courseids: [course_id] } : {});
        
        let imported = 0;
        for (const course of (data.courses || [])) {
            for (const assign of (course.assignments || [])) {
                const due = assign.duedate ? new Date(assign.duedate * 1000).toISOString() : null;
                await app.db.query(
                    `INSERT INTO tasks (title, description, due_at, external_id, external_source, status, priority)
                     VALUES ($1, $2, $3, $4, moodle, pending, medium)
                     ON CONFLICT DO NOTHING`,
                    [assign.name, assign.intro || "", due, `moodle:assign:${assign.id}`]
                );
                imported++;
            }
        }
        return { status: "ok", imported };
    });

    // Get completion status
    app.get("/connectors/moodle/completion/:courseId", async (req) => {
        const { url, token, userid } = req.query;
        const data = await moodleCall(url || MOODLE_URL, token, "core_completion_get_course_completion_status",
            { courseid: req.params.courseId, userid: userid || "2" });
        return { status: "ok", data };
    });

    // Get grades
    app.get("/connectors/moodle/grades/:courseId", async (req) => {
        const { url, token, userid } = req.query;
        const data = await moodleCall(url || MOODLE_URL, token, "gradereport_user_get_grade_items",
            { courseid: req.params.courseId, userid: userid || "2" });
        return { status: "ok", data };
    });

    // Webhook from Moodle (events API)
    app.post("/connectors/moodle/webhook", async (req) => {
        const { eventname, courseid, userid, objectid } = req.body;
        app.log.info({ eventname, courseid, userid }, "Moodle webhook");

        if (eventname === "\\mod_assign\\event\\assessable_submitted") {
            await app.db.query(
                `UPDATE tasks SET status = completed, completed_at = NOW(), updated_at = NOW()
                 WHERE external_id = $1`,
                [`moodle:assign:${objectid}`]
            );
        }
        return { status: "received" };
    });
}

module.exports = moodleConnector;
