const express = require('express');
const Customer = require('../models/Customer');
const router = express.Router();

router.post('/', async (req, res) => {
  try {
    const { customerNumber, firstName, lastName, telephone, address } = req.body;
    const customer = await Customer.create({ customerNumber, firstName, lastName, telephone, address });
    res.status(201).json(customer);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

router.get('/', async (req, res) => {
  try {
    const customers = await Customer.find().sort({ customerNumber: 1 });
    res.json(customers);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const { customerNumber, firstName, lastName, telephone, address } = req.body;
    const updated = await Customer.findByIdAndUpdate(
      req.params.id,
      { customerNumber, firstName, lastName, telephone, address },
      { new: true, runValidators: true }
    );

    if (!updated) return res.status(404).json({ message: 'Customer not found' });
    res.json(updated);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

router.delete('/:id', async (req, res) => {
  try {
    const deleted = await Customer.findByIdAndDelete(req.params.id);
    if (!deleted) return res.status(404).json({ message: 'Customer not found' });
    res.json({ message: 'Customer deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;

