const path = require("path");
const createCsvWriter = require("csv-writer").createObjectCsvWriter;
const Appointment = require("../models/Appointment");

const generateAppointmentCSV = async (req, res) => {
  try {
    const appointments = await Appointment.find();
    const groupedData = appointments.reduce((acc, appointment) => {
      if (!acc[appointment.facultyId]) {
        acc[appointment.facultyId] = {
          facultyId: appointment.facultyId,
          facultyName: appointment.facultyName,
          tasks: [],
        };
      }
      acc[appointment.facultyId].tasks.push({
        courseId: appointment.courseId,
        courseName: appointment.courseName,
        task: appointment.task,
      });
      return acc;
    }, {});

    const csvData = [];
    Object.values(groupedData).forEach(({ facultyId, facultyName, tasks }) => {
      tasks.forEach(({ courseId, courseName, task }) => {
        csvData.push({ facultyId, facultyName, courseId, courseName, task });
      });
    });

    const csvWriter = createCsvWriter({
      path: path.join(__dirname, "../generated_csv/appointments.csv"),
      header: [
        { id: "facultyId", title: "Faculty ID" },
        { id: "facultyName", title: "Faculty Name" },
        { id: "courseId", title: "Course ID" },
        { id: "courseName", title: "Course Name" },
        { id: "task", title: "Task" },
      ],
    });

    await csvWriter.writeRecords(csvData);
    res.status(200).json({ message: "CSV generated successfully", path: "./generated_csv/appointments.csv" });
  } catch (error) {
    console.error("Error generating CSV:", error);
    res.status(500).json({ message: "Failed to generate CSV" });
  }
};

module.exports = { generateAppointmentCSV };
