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

router.get("/consolidated-table", async (req, res) => {
  try {
    const appointments = await Appointment.find();
    const courses = await Course.find();
    const faculties = await Faculty.find();

    // Group by facultyId and courseId
    const groupedData = {};

    appointments.forEach((appointment) => {
      const key = `${appointment.facultyId}-${appointment.courseId}-${appointment.academicYear}-${appointment.examPeriod}`;
      if (!groupedData[key]) {
        groupedData[key] = {
          facultyId: appointment.facultyId,
          courseId: appointment.courseId,
          facultyName: appointment.facultyName,
          courseName: appointment.courseName,
          semester: "",
          examType: "",
          academicYear: appointment.academicYear, // Added from appointment
          examPeriod: appointment.examPeriod,     // Added from appointment
          program: "",  
          marks: "100+25", // Dummy value, replace with actual logic
          affiliation: "KJSCE", // Replace with actual value
          qualification: "M.E.", // Replace with actual value
          experience: "20+", // Dummy value
          tasks: new Set(), // Use a set to avoid duplicate tasks
        };
      }   
      groupedData[key].tasks.add(appointment.task);
    });


    // Add course details to the grouped data
    Object.values(groupedData).forEach((data) => {
      const course = courses.find((c) => c.courseId === data.courseId);
      if (course) {
        data.semester = course.semester;
        data.examType = course.scheme;
        data.program = course.program;
      }
    });

    // Format the tasks into separate columns
    const tableData = Object.values(groupedData).map((data, index) => ({
      srNo: index + 1,
      semester: data.semester,
      courseCode: data.courseId,
      courseName: data.courseName,
      examType: data.examType,
      academicYear: data.academicYear,
      examPeriod : data.examPeriod,
      program : data.program,
      marks: data.marks,
      Name: data.facultyName,
      affiliation: data.affiliation,
      qualification: data.qualification,
      experience: data.experience,
      oralPractical: data.tasks.has("oralsPracticals") ? "✔" : "",
      assessment: data.tasks.has("assessment") ? "✔" : "",
      reassessment: data.tasks.has("reassessment") ? "✔" : "",
      paperSetting: data.tasks.has("paperSetting") ? "✔" : "",
      moderation: data.tasks.has("moderation") ? "✔" : "",
      pwdPaperSetting: data.tasks.has("pwdPaperSetter") ? "✔" : "",
      facultyId: `${data.facultyId}`
    }));

    res.status(200).json(tableData);
  } catch (error) {
    console.error("Error fetching consolidated table data:", error);
    res.status(500).json({ message: "Failed to fetch consolidated table data" });
  }
});

router.get("/course-consolidated", async (req, res) => {
  try {
    const appointments = await Appointment.find();
    const courses = await Course.find();

    // Group appointments by courseId and task
    const groupedByCourse = {};

    appointments.forEach((appointment) => {
      const courseId = appointment.courseId;

      if (!groupedByCourse[courseId]) {
        groupedByCourse[courseId] = {
          courseId: courseId,
          courseName: appointment.courseName,
          tasks: {
            oralsPracticals: new Set(),
            assessment: new Set(),
            reassessment: new Set(),
            paperSetting: new Set(),
            moderation: new Set(),
            pwdPaperSetter: new Set(),
          },
          semester: "",
          examType: "",
          year: "",
        };
      }

      // Add the faculty name to the appropriate task
      if (appointment.task && groupedByCourse[courseId].tasks[appointment.task]) {
        groupedByCourse[courseId].tasks[appointment.task].add(JSON.stringify({ facultyId: appointment.facultyId, facultyName: appointment.facultyName }));
      }
    });

    // Add course details to grouped data
    Object.values(groupedByCourse).forEach((group) => {
      const course = courses.find((c) => c.courseId === group.courseId);

      if (course) {
        group.semester = course.semester;
        group.examType = course.scheme;
        group.year = course.program;
      }
    });

    // Format the consolidated data
    const consolidatedData = Object.values(groupedByCourse).map((course, index) => ({
      courseCode: course.courseId,
      courseName: course.courseName,
      semester: course.semester,
      examType: course.examType,
      year: course.year,
      oralPracticalTeachers: Array.from(course.tasks.oralsPracticals).map((data) => JSON.parse(data)),
      assessmentTeachers: Array.from(course.tasks.assessment).map((data) => JSON.parse(data)),
      reassessmentTeachers: Array.from(course.tasks.reassessment).map((data) => JSON.parse(data)),
      paperSettingTeachers: Array.from(course.tasks.paperSetting).map((data) => JSON.parse(data)),
      moderationTeachers: Array.from(course.tasks.moderation).map((data) => JSON.parse(data)),
      pwdPaperSettingTeachers: Array.from(course.tasks.pwdPaperSetter).map((data) => JSON.parse(data)),
    }));

    res.status(200).json(consolidatedData);
  } catch (error) {
    console.error("Error fetching course consolidated data:", error);
    res.status(500).json({ message: "Failed to fetch course consolidated data" });
  }
});

router.get("/department-consolidated", async (req, res) => {
  try {
    const appointments = await Appointment.find();
    const courses = await Course.find();

    // Group appointments by department and course
    const groupedByDepartment = {};

    appointments.forEach((appointment) => {
      const course = courses.find((c) => c.courseId === appointment.courseId);

      if (!course) return; // Skip if course not found

      const department = course.department;

      if (!groupedByDepartment[department]) {
        groupedByDepartment[department] = {
          department: department,
          courses: [],
        };
      }

      // Find or create the course in the department
      let courseData = groupedByDepartment[department].courses.find(
        (c) => c.courseCode === appointment.courseId
      );

      if (!courseData) {
        courseData = {
          courseCode: appointment.courseId,
          courseName: appointment.courseName,
          semester: course.semester,
          examType: course.scheme,
          year: course.program,
          oralPracticalTeachers: [],
          assessmentTeachers: [],
          reassessmentTeachers: [],
          paperSettingTeachers: [],
          moderationTeachers: [],
          pwdPaperSettingTeachers: [],
        };
        groupedByDepartment[department].courses.push(courseData);
      }

      // Add the faculty name to the appropriate task
      if (appointment.task === "oralsPracticals") {
        courseData.oralPracticalTeachers.push(appointment.facultyName);
      } else if (appointment.task === "assessment") {
        courseData.assessmentTeachers.push(appointment.facultyName);
      } else if (appointment.task === "reassessment") {
        courseData.reassessmentTeachers.push(appointment.facultyName);
      } else if (appointment.task === "paperSetting") {
        courseData.paperSettingTeachers.push(appointment.facultyName);
      } else if (appointment.task === "moderation") {
        courseData.moderationTeachers.push(appointment.facultyName);
      } else if (appointment.task === "pwdPaperSetter") {
        courseData.pwdPaperSettingTeachers.push(appointment.facultyName);
      }
    });

    // Convert to array format
    const consolidatedData = Object.values(groupedByDepartment);

    res.status(200).json(consolidatedData);
  } catch (error) {
    console.error("Error fetching department consolidated data:", error);
    res.status(500).json({ message: "Failed to fetch department consolidated data" });
  }
});

router.get("/panel-consolidated", async (req, res) => {
  try {
    const courses = await Course.find();
    const faculties = await Faculty.find();

    // Create a structure where each course has its associated faculty
    const consolidatedData = courses.map((course) => {
      return {
        courseId: course.courseId,
        courseName: course.courseName,
        semester: course.semester,
        examType: course.scheme,
        program: course.program,
        faculty: faculties
          .filter((faculty) => faculty.courses.includes(course.courseId))
          .map((faculty) => ({
            facultyId: faculty.facultyId,
            name: faculty.name,
            email: faculty.email,
            qualification: faculty.qualification,
            experience: faculty.experience,
          })),
      };
    });

    res.status(200).json(consolidatedData);
  } catch (error) {
    console.error("Error fetching panel consolidated data:", error);
    res.status(500).json({ message: "Failed to fetch panel consolidated data" });
  }
});


module.exports = router;
