const mongoose = require("mongoose"); const express = require("express"); const Course = require("../mongoose/models/courses"); const usersRouter = new express.Router(); // Get all courses usersRouter.get("/courses/get", async (req, res) => { try { const courses = await Course.find({}); res.status(200).send(courses); } catch (error) { res.status(400).send({ error: "Failed to fetch courses" }); } }); // Enroll in a course usersRouter.post("/courses/enroll/:id", async (req, res) => { try { const course = await Course.findById(req.params.id); if (!course) { return res.status(404).send({ error: "Course not found" }); } if (course.isApplied) { return res.status(403).send({ error: "Already enrolled in this course" }); } course.isApplied = true; await course.save(); res.status(200).send({ message: "Enrolled successfully" }); } catch (error) { res.status(400).send({ error: "Failed to enroll in the course" }); } }); // Drop a course usersRouter.delete("/courses/drop/:id", async (req, res) => { try { const course = await Course.findById(req.params.id); if (!course) { return res.status(404).send({ error: "Course not found" }); } if (!course.isApplied) { return res.status(403).send({ error: "Cannot drop an unenrolled course" }); } course.isApplied = false; await course.save(); res.status(200).send({ message: "Dropped the course successfully" }); } catch (error) { res.status(400).send({ error: "Failed to drop the course" }); } }); // Rate a course usersRouter.patch("/courses/rating/:id", async (req, res) => { try { const { rating } = req.body; if (!rating || rating < 1 || rating > 5) { return res.status(400).send({ error: "Invalid rating" }); } const course = await Course.findById(req.params.id); if (!course) { return res.status(404).send({ error: "Course not found" }); } if (!course.isApplied) { return res.status(403).send({ error: "Cannot rate an unenrolled course" }); } if (course.isRated) { return res.status(403).send({ error: "Course has already been rated" }); } // Update course rating const totalRating = course.rating * course.noOfRatings; const newTotalRating = totalRating + rating; course.noOfRatings += 1; course.rating = (newTotalRating / course.noOfRatings).toFixed(1); course.isRated = true; await course.save(); res.status(200).send({ message: "Rating added successfully" }); } catch (error) { res.status(400).send({ error: "Failed to rate the course" }); } }); module.exports = usersRouter;