const CarMake = require('../models/car_makes.js');
const CarModel = require('../models/car_models.js');

// Get all makes
// This function retrieves all car makes from the database and sends them as a response.
exports.getMakes = async (req, res) => {
    try {
      const docs = await CarMake.find()
        .select("make_name")
        .lean();
  
      const makes = docs.map((d) => ({
        label: d.make_name,
      }));
  
      return res.status(200).json(makes);
    } catch (error) {
      console.error("Server error retrieving makes:", error);
      return res.status(500).json({
        message: "Server error retrieving makes",
        error: error.message,
      });
    }
  };

exports.getModelsByMake = async (req, res) => {
    try {
      const { make } = req.query;
      if (!make) {
        return res.status(400).json({ message: "Missing `make` parameter" });
      }
  
      const models = await CarModel.distinct("model", { make });
  
      if (models.length === 0) {
        return res.status(404).json({ message: "No models found for this make" });
      }
  
      const payload = models.map((m) => ({ label: m }));
      return res.status(200).json(payload);
  
    } catch (err) {
      console.error("Error retrieving models:", err);
      return res
        .status(500)
        .json({ message: "Server error retrieving models", error: err.message });
    }
};
  

exports.getYearsByModel = async (req, res) => {
  try {
    const { make, model } = req.query;
    if (!make || !model) {
      return res
        .status(400)
        .json({ message: "Missing required `make` and/or `model` query parameter" });
    }

    // Grab all distinct year values for that make+model combo
    const rawYears = await CarModel.distinct("year", { make, model });
    if (rawYears.length === 0) {
      return res
        .status(404)
        .json({ message: "No years found for this make/model combination" });
    }

    // Convert numbers to strings, sort descending, and wrap as { label }
    const payload = rawYears
      .map((y) => y.toString())
      .sort((a, b) => Number(b) - Number(a))
      .map((y) => ({ label: y }));

    return res.status(200).json(payload);

  } catch (error) {
    console.error("Server error retrieving years:", error);
    return res.status(500).json({
      message: "Server error retrieving years",
      error: error.message,
    });
  }
};