const Coupon = require("../models/couponModel");
const APIFeatures = require("../utils/ApiFeatures"); // Assuming you have this

// 1. Get All Coupons (Admin)
exports.getAllCoupons = async (req, res) => {
  try {
    const features = new APIFeatures(Coupon.find(), req.query)
      .filter()
      .sort()
      .paginate();

    // ✅ POPULATE CAMPUS NAME
    // We populate only 'name' to keep payload light
    features.query = features.query.populate("campus", "name");

    const coupons = await features.query;

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

// 2. Create Coupon (Admin)
exports.createCoupon = async (req, res) => {
  try {
    const newCoupon = await Coupon.create(req.body);
    res.status(201).json({
      status: "success",
      data: { coupon: newCoupon },
    });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

// 3. Delete Coupon
exports.deleteCoupon = async (req, res) => {
  try {
    await Coupon.findByIdAndDelete(req.params.id);
    res.status(204).json({ status: "success", data: null });
  } catch (err) {
    res.status(400).json({ status: "fail", message: err.message });
  }
};

exports.updateCoupon = async (req, res) => {
  try {
    const coupon = await Coupon.findByIdAndUpdate(req.params.id, req.body, {
      new: true,
      runValidators: true,
    });

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

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