const express = require("express");
const Course = require("../models/Course");
const verifyAdmin = require("../middleware/verifyAdmin");

const router = express.Router();

router.get("/", async (req, res) => {
  try {
    const filter = {};

    if (req.query.department) filter.department = req.query.department;
    if (req.query.program) filter.program = req.query.program;
    if (req.query.semester) filter.semester = Number(req.query.semester); // Convert to number if needed
    if (req.query.scheme) filter.scheme = req.query.scheme;

    const courses = await Course.find(filter);
    res.json(courses);
  } catch (error) {
    console.error("Error fetching courses:", error);
    res.status(500).json({ error: "Failed to fetch courses" });
  }
});

// Get course by ID
router.get("/:id", async (req, res) => {
  try {
    const course = await Course.findOne({ courseId: req.params.id });
    if (!course) {
      return res.status(404).json({ error: "Course not found" });
    }
    res.json(course);
  } catch (error) {
    console.error("Error fetching course:", error);
    res.status(500).json({ error: "Failed to fetch course" });
  }
});

// Update course status route
router.patch(":courseId", async (req, res) => {
  try {
    const { courseId } = req.params; // Extract courseId from params
    const { status } = req.body; // Extract status from body

    console.log("Request params:", req.params);
    console.log("Request body:", req.body);

    // Validate status
    if (!["submitted", "not submitted"].includes(status.toLowerCase())) {
      return res.status(400).json({ message: "Invalid status value" });
    }

    // Find and update the course by courseId
    const updatedCourse = await Course.findOneAndUpdate(
      { courseId }, // Query by courseId field
      { status: status.toLowerCase() }, // Set status (convert to lowercase)
      { new: true } // Return the updated document
    );

    if (!updatedCourse) {
      console.error("Course not found:", courseId);
      return res.status(404).json({ message: "Course not found" });
    }

    console.log("Updated course:", updatedCourse);
    res.status(200).json(updatedCourse);
  } catch (error) {
    console.error("Error updating course status:", error.message);
    res.status(500).json({ message: "Internal server error" });
  }
});

//update a course
router.put("/:courseId", verifyAdmin, async (req, res) => {
  try {
    const updatedCourse = await Course.findOneAndUpdate(
      { courseId: req.params.courseId },
      req.body,
      { new: true }
    );
    if (!updatedCourse) {
      return res.status(404).json({ error: "Course not found" });
    }
    res.json(updatedCourse);
  } catch (error) {
    console.error("Error updating course:", error);
    res.status(500).json({ error: "Failed to update course" });
  }
});

//delete
router.delete("/:courseId", verifyAdmin, async (req, res) => {
  try {
    const deletedCourse = await Course.findOneAndDelete({
      courseId: req.params.courseId,
    });
    if (!deletedCourse) {
      return res.status(404).json({ error: "Course not found" });
    }
    res.json({ message: "Course deleted successfully" });
  } catch (error) {
    console.error("Error deleting course:", error);
    res.status(500).json({ error: "Failed to delete course" });
  }
});

// add a new course
router.post("/", verifyAdmin, async (req, res) => {
  try {
    const { courseId, name, department, program, scheme, semester, status } =
      req.body;

    // Check if a course with the same courseId already exists
    const existingCourse = await Course.findOne({ courseId });
    if (existingCourse) {
      return res.status(400).json({ error: "Course ID already exists" });
    }

    const newCourse = new Course({
      courseId,
      name,
      department,
      program,
      scheme,
      semester,
      status,
    });

    await newCourse.save();
    res
      .status(201)
      .json({ message: "Course added successfully", course: newCourse });
  } catch (error) {
    console.error("Error adding course:", error);
    res.status(500).json({ error: "Failed to add course" });
  }
});

module.exports = router;
