const { Customer, Booking } = require('../models');

class CustomerController {
  async create(req, res, next) {
    try {
      const { email } = req.body;
      const existing = await Customer.findOne({ where: { email } });

      if (existing) {
        return res.status(409).json({ error: 'Customer with this email already exists', customer: existing });
      }

      const customer = await Customer.create(req.body);
      res.status(201).json({ customer });
    } catch (error) {
      next(error);
    }
  }

  async getById(req, res, next) {
    try {
      const customer = await Customer.findByPk(req.params.id, {
        include: [{ model: Booking }],
      });
      if (!customer) {
        return res.status(404).json({ error: 'Customer not found' });
      }
      res.json({ customer });
    } catch (error) {
      next(error);
    }
  }

  async getAll(req, res, next) {
    try {
      const customers = await Customer.findAll({
        order: [['created_at', 'DESC']],
      });
      res.json({ customers });
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new CustomerController();
