const Counter = require("../model/Counter");

/**
 * Atomically generates the next sequential number for a given entity.
 * @param {string} entityKey - unique key stored in counters collection (e.g. "car")
 * @param {string} prefix    - human-readable prefix (e.g. "CAR")
 * @returns {Promise<string>} e.g. "CAR-0001"
 */
async function generateSequence(entityKey, prefix) {
  const counter = await Counter.findByIdAndUpdate(
    entityKey,
    { $inc: { seq: 1 } },
    { new: true, upsert: true }
  );
  const paddedNumber = String(counter.seq).padStart(4, "0");
  return `${prefix}-${paddedNumber}`;
}

module.exports = generateSequence;
