const express = require("express");
const router = express.Router();
const Appointment = require("../models/Appointment");
const Faculty = require("../models/Faculty");
const Course = require("../models/Course");

// Save multiple appointments
router.post("/", async (req, res) => {
  try {
    const { appointments } = req.body;
    if (!appointments || !Array.isArray(appointments)) {
      return res.status(400).json({ error: "Invalid or missing data" });
    }

    const savedAppointments = [];
    for (const appointment of appointments) {
      const { facultyId, courseId, tasks, examPeriod, academicYear } = appointment;

      if (
        !facultyId ||
        !courseId ||
        !Array.isArray(tasks) ||
        tasks.length === 0 ||
        !examPeriod
      ) {
        return res.status(400).json({ error: "Invalid appointment data" });
      }

      const faculty = await Faculty.findOne({ facultyId });
      const course = await Course.findOne({ courseId });

      if (!faculty || !course) {
        return res.status(404).json({
          error: `Faculty or Course not found for facultyId: ${facultyId}, courseId: ${courseId}`,
        });
      }

      for (const task of tasks) {
        const newAppointment = new Appointment({
          facultyId,
          facultyName: faculty.name,
          courseId,
          courseName: course.name,
          task,
          examPeriod,
          academicYear,
        });
        const savedAppointment = await newAppointment.save();
        savedAppointments.push(savedAppointment);
      }
    }

    res.status(201).json(savedAppointments);
  } catch (error) {
    console.error("Error saving appointments:", error);
    res.status(500).json({ error: "Failed to save appointments" });
  }
});

// Get all appointments
router.get("/", async (req, res) => {
  const { academicYear } = req.query;
  try {
    const appointments = await Appointment.find({ academicYear });
    res.json(appointments);
  } catch (error) {
    console.error("Error fetching appointments:", error);
    res.status(500).json({ error: "Failed to fetch appointments" });
  }
});

module.exports = router;
