const Staff = require("../models/staffModel");
const Instructor = require("../models/instructorModel"); // ✅ Imported Instructor Model
const StaffRole = require("../models/staffRoleModel");
const APIFeatures = require("../utils/ApiFeatures");
const {
  deleteOldStaffPhoto,
} = require("../storage/middlewareStorage/uploadStaffMedia");

exports.getAllStaff = async (req, res) => {
  try {
    // 1. Prepare Staff Query
    const features = new APIFeatures(Staff.find(), req.query)
      .filter()
      .sort()
      .limitFields()
      .paginate();

    // 2. Run BOTH queries in parallel (Fastest way)
    const [staff, roles] = await Promise.all([
      features.query,
      StaffRole.find(), // Fetch all roles immediately
    ]);

    res.status(200).json({
      status: "success",
      results: staff.length,
      data: {
        staff,
        roles, // Send roles in the same response
      },
    });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.getStaffMember = async (req, res) => {
  try {
    const staffMember = await Staff.findById(req.params.id);
    if (!staffMember) {
      return res.status(404).json({ message: "Staff member not found" });
    }
    res.status(200).json({ status: "success", data: { staffMember } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.createStaff = async (req, res) => {
  try {
    if (req.file) req.body.photo = req.file.filename;

    // 1. Find the Role Name associated with the passed role ID
    const role = await StaffRole.findById(req.body.role);
    if (!role)
      return res
        .status(400)
        .json({ status: "fail", message: "Invalid Role ID" });

    let newStaff;

    // 2. If Role is "Instructor", create using Instructor Model
    if (role.name.toLowerCase() === "instructor") {
      // This sets kind: 'Instructor' and enables the 'courses' virtual
      newStaff = await Instructor.create(req.body);
    } else {
      // Otherwise, create as regular Staff (kind: 'Staff')
      newStaff = await Staff.create(req.body);
    }

    // ✅ FIX: Populate the role immediately so frontend gets the Name, not just ID
    await newStaff.populate({ path: "role", select: "name" });

    res.status(201).json({ status: "success", data: { staff: newStaff } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.updateStaff = async (req, res) => {
  try {
    // We first find the document using the base Staff model
    let staffMember = await Staff.findById(req.params.id);
    if (!staffMember)
      return res.status(404).json({ message: "Staff not found" });

    if (req.file) {
      // Delete old photo before updating
      await deleteOldStaffPhoto(staffMember.photo);
      req.body.photo = req.file.filename;
    }

    // Standard update
    const updatedStaff = await Staff.findByIdAndUpdate(
      req.params.id,
      req.body,
      {
        new: true,
        runValidators: true,
      }
    ).populate({ path: "role", select: "name" }); // ✅ FIX: Populate immediately

    res.status(200).json({ status: "success", data: { staff: updatedStaff } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.deleteStaff = async (req, res) => {
  try {
    const staffMember = await Staff.findById(req.params.id);
    if (!staffMember)
      return res.status(404).json({ message: "Staff not found" });

    // Delete photo
    await deleteOldStaffPhoto(staffMember.photo);
    await Staff.findByIdAndDelete(req.params.id);

    res.status(204).json({ status: "success", data: null });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};
