const Instructor = require("../models/instructorModel");
const APIFeatures = require("../utils/ApiFeatures");
const {
  deleteOldStaffPhoto,
} = require("../storage/middlewareStorage/uploadStaffMedia"); // Reuse staff media logic

// --- Helper to handle file upload ---
const processUploadedFiles = (req) => {
  if (req.file) req.body.photo = req.file.filename;
};

exports.getAllInstructors = async (req, res) => {
  try {
    const features = new APIFeatures(Instructor.find(), req.query)
      .filter()
      .sort()
      .limitFields()
      .paginate();

    // Automatically filters for kind="Instructor"
    const instructors = await features.query;

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

exports.getInstructor = async (req, res) => {
  try {
    const instructor = await Instructor.findById(req.params.id); // Populates courses via middleware
    if (!instructor)
      return res.status(404).json({ message: "Instructor not found" });
    res.status(200).json({ status: "success", data: { instructor } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.createInstructor = async (req, res) => {
  try {
    processUploadedFiles(req);
    // ✅ CRITICAL: Using Instructor.create() sets 'kind' to 'Instructor'
    const newInstructor = await Instructor.create(req.body);
    res
      .status(201)
      .json({ status: "success", data: { instructor: newInstructor } });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

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

    if (req.file) {
      await deleteOldStaffPhoto(instructor.photo);
      req.body.photo = req.file.filename;
    }

    const updated = await Instructor.findByIdAndUpdate(
      req.params.id,
      req.body,
      {
        new: true,
        runValidators: true,
      }
    );

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

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

    await deleteOldStaffPhoto(instructor.photo);
    await Instructor.findByIdAndDelete(req.params.id);

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