const Code = require("../../models/Code");

// Create a new code
async function createCode(req, res) {
  const { code, description, discountPercentage } = req.body;
  try {
    const newCode = new Code({
      code,
      description,
      discountPercentage,
      createdBy: req.user.id,
    });
    await newCode.save();
    res.status(201).json(newCode);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
}

// Get all codes
async function getAllCodes(req, res) {
  try {
    const codes = await Code.find().populate("createdBy", "username");
    res.status(200).json(codes);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
}

// Get a code by ID
async function getCodeById(req, res) {
  try {
    const code = await Code.findById(req.params.id).populate(
      "createdBy",
      "username"
    );
    if (!code) return res.status(404).json({ message: "Code not found" });
    res.status(200).json(code);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
}

// Update code (partial or full update)
async function updateCode(req, res) {
  const { code, description, isActive, discountPercentage } = req.body;
  const updates = {};

  if (code !== undefined) updates.code = code;
  if (description !== undefined) updates.description = description;
  if (isActive !== undefined) updates.isActive = isActive;
  if (discountPercentage !== undefined)
    updates.discountPercentage = discountPercentage;

  try {
    const updatedCode = await Code.findByIdAndUpdate(
      req.params.id,
      { $set: updates },
      { new: true }
    );
    if (!updatedCode)
      return res.status(404).json({ message: "Code not found" });
    res.status(200).json(updatedCode);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
}

// Export all functions
module.exports = {
  createCode,
  getAllCodes,
  getCodeById,
  updateCode,
};
