const Campus = require("../models/campusModel");

// --- Helper: Process Uploaded Files ---
const processUploadedFiles = (req) => {
  if (!req.files) return;
  if (req.files.coverImage)
    req.body.coverImage = req.files.coverImage[0].filename;
  if (req.files.promoVideo)
    req.body.promoVideo = req.files.promoVideo[0].filename;
  if (req.files.images)
    req.body.images = req.files.images.map((file) => file.filename);
};

// --- CRUD Controllers ---

exports.getAllCampuses = async (req, res) => {
  try {
    // 🔥 FIX: We MUST populate 'courses' so the frontend carousel works.
    // To keep it "Safe" and fast, we ONLY select the fields needed for the card.
    const campuses = await Campus.find().populate({
      path: "courses",
      select: "name price coverImage mode instructors", // <--- Only load what is needed
    });

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

exports.getCampus = async (req, res) => {
  try {
    // ✅ POPULATE VIRTUAL (Already Correct)
    const campus = await Campus.findById(req.params.id).populate({
      path: "courses",
      select: "name price coverImage mode instructors",
    });

    if (!campus) {
      return res
        .status(404)
        .json({ status: "fail", message: "Campus not found" });
    }

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

exports.createCampus = async (req, res) => {
  try {
    processUploadedFiles(req);
    const newCampus = await Campus.create(req.body);
    res.status(201).json({ status: "success", data: { campus: newCampus } });
  } catch (err) {
    res
      .status(400)
      .json({ status: "fail", message: "Invalid data", error: err.message });
  }
};

exports.updateCampus = async (req, res) => {
  try {
    processUploadedFiles(req);
    const campus = await Campus.findByIdAndUpdate(req.params.id, req.body, {
      new: true,
      runValidators: true,
    });

    if (!campus) return res.status(404).json({ message: "Campus not found" });

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

exports.deleteCampus = async (req, res) => {
  try {
    const campus = await Campus.findByIdAndDelete(req.params.id);
    if (!campus) return res.status(404).json({ message: "Campus not found" });
    res.status(204).json({ status: "success", data: null });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};
