const express = require("express");
const Faculty = require("../models/Faculty");

const router = express.Router();

// Get all faculty members
router.get("/", async (req, res) => {
  try {
    const faculties = await Faculty.find();
    res.status(200).json(faculties);
  } catch (error) {
    console.error("Error fetching faculty members:", error.message);
    res.status(500).json({ error: "Failed to fetch faculty members" });
  }
});

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

// Add new faculty
router.post("/", async (req, res) => {
  const { facultyId, name, email, department, program, courses } = req.body;
  try {
    const newFaculty = new Faculty({
      facultyId,
      name,
      email,
      department,
      program,
      courses,
    });
    await newFaculty.save();
    res.status(201).json(newFaculty);
  } catch (error) {
    console.error("Error adding new faculty:", error.message);
    res.status(500).json({ error: "Failed to add faculty member" });
  }
});

//Update faculty

router.put("/:id", async (req, res) => {
  try {
    const updatedFaculty = await Faculty.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    );

    if (!updatedFaculty) {
      return res.status(404).json({ error: "Faculty member not found" });
    }

    res.status(200).json(updatedFaculty);
  } catch (error) {
    console.error("Error updating faculty member:", error.message);
    res.status(500).json({ error: "Failed to update faculty member" });
  }
});

// Delete faculty by ID
router.delete("/:id", async (req, res) => {
  try {
    const deletedFaculty = await Faculty.findByIdAndDelete(req.params.id);
    if (!deletedFaculty) {
      return res.status(404).json({ error: "Faculty member not found" });
    }

    res.status(200).json({ message: "Faculty member deleted successfully" });
  } catch (error) {
    console.error("Error deleting faculty member:", error.message);
    res.status(500).json({ error: "Failed to delete faculty member" });
  }
});


module.exports = router;
