const { getCollections, getNextSequence } = require('../config/db');

// Get all customers
const getCustomers = async (req, res) => {
  try {
    const { customers } = await getCollections();
    const { search } = req.query;

    let cursor = customers.find({});

    if (search) {
      cursor = customers.find({
        $or: [
          { full_name: { $regex: search, $options: 'i' } },
          { phone_number: { $regex: search, $options: 'i' } },
          { email: { $regex: search, $options: 'i' } }
        ]
      });
    }

    const rows = await cursor.sort({ registration_date: -1 }).toArray();
    res.json(rows);
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

// Get single customer
const getCustomer = async (req, res) => {
  try {
    const { customers } = await getCollections();
    const row = await customers.findOne({ customer_id: Number(req.params.id) });
    if (!row) return res.status(404).json({ message: 'Customer not found.' });
    res.json(row);
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

// Register customer
const addCustomer = async (req, res) => {
  const { full_name, phone_number, email, address } = req.body;
  if (!full_name || !phone_number)
    return res.status(400).json({ message: 'Full name and phone number are required.' });

  try {
    const { customers } = await getCollections();

    const customer_id = await getNextSequence('customers');

    await customers.insertOne({
      customer_id,
      full_name,
      phone_number,
      email: email || null,
      address: address || null,
      registration_date: new Date()
    });

    res.status(201).json({ message: 'Customer registered.', customer_id });
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

// Update customer
const updateCustomer = async (req, res) => {
  const { full_name, phone_number, email, address } = req.body;
  try {
    const { customers } = await getCollections();

    const result = await customers.updateOne(
      { customer_id: Number(req.params.id) },
      { $set: { full_name, phone_number, email, address } }
    );

    if (result.matchedCount === 0) return res.status(404).json({ message: 'Customer not found.' });
    res.json({ message: 'Customer updated.' });
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

// Delete customer
const deleteCustomer = async (req, res) => {
  try {
    const { customers } = await getCollections();

    const result = await customers.deleteOne({ customer_id: Number(req.params.id) });
    if (result.deletedCount === 0) return res.status(404).json({ message: 'Customer not found.' });

    res.json({ message: 'Customer deleted.' });
  } catch (err) {
    res.status(500).json({ message: 'Server error.' });
  }
};

module.exports = { getCustomers, getCustomer, addCustomer, updateCustomer, deleteCustomer };

