const ServiceRecord = require("../model/ServiceRecord");
const generateSequence = require("../utils/generateSequence");

const createServiceRecord = async (req, res) => {
  try {
    const userId = req.session?.user?.id;
    const recordNumber = await generateSequence("serviceRecord", "REC");
    const record = await ServiceRecord.create({ ...req.body, userId, recordNumber });
    const populated = await record.populate("car service");
    return res.status(201).json(populated);
  } catch (error) {
    return res.status(400).json({ message: error.message });
  }
};

const getServiceRecords = async (req, res) => {
  const userId = req.session?.user?.id;
  const records = await ServiceRecord.find({ userId })
    .populate("car service")
    .sort({ createdAt: -1 });
  return res.json(records);
};

const updateServiceRecord = async (req, res) => {
  try {
    const userId = req.session?.user?.id;
    const record = await ServiceRecord.findOneAndUpdate(
      { _id: req.params.id, userId },
      req.body,
      {
        new: true,
        runValidators: true,
      }
    ).populate("car service");
    if (!record) return res.status(404).json({ message: "Record not found" });
    return res.json(record);
  } catch (error) {
    return res.status(400).json({ message: error.message });
  }
};

const deleteServiceRecord = async (req, res) => {
  const userId = req.session?.user?.id;
  const record = await ServiceRecord.findOneAndDelete({ _id: req.params.id, userId });
  if (!record) return res.status(404).json({ message: "Record not found" });
  return res.json({ message: "Record deleted" });
};


module.exports = {
  createServiceRecord,
  getServiceRecords,
  updateServiceRecord,
  deleteServiceRecord,
};
