const Customer = require('../models/customer');

exports.addcustomer = async (req, res) => {
  try {
    const { customerNumber, firstName, lastName, telephone, address } = req.body;

    const existingCustomer = await Customer.findOne({ customerNumber });
    if (existingCustomer) {
      return res.status(409).json({ message: 'Customer number already exists' });
    }

    const customer = await Customer.create({
      customerNumber,
      firstName,
      lastName,
      telephone,
      address,
    });

    res.status(201).json(customer);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.getcustomers = async (req, res) => {
  try {
    const customers = await Customer.find().sort({ createdAt: -1 });
    res.json(customers);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.getcustomerbyid = async (req, res) => {
  try {
    const customer = await Customer.findById(req.params.id);
    if (!customer) {
      return res.status(404).json({ message: 'Customer not found' });
    }
    res.json(customer);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
