const Customer = require('../models/Customer');
const paymentHistory =require('../models/PaymentHistory')
const mongoose = require('mongoose');
// Fetch all customers
exports.getCustomers = async (req, res) => {
  try {
    const companyId=req.query.companyId;

   
   
            const objectIdCompanyId = new mongoose.Types.ObjectId(companyId);
         //   console.log('ObjectId:', objectIdCompanyId); // Log the ObjectId to verify
    
            const matches = await Customer.find({ companyId: objectIdCompanyId });
         //   console.log('Matched Customers:', matches); // Log the matched customers
    
            const customers = await Customer.aggregate([
                {
                    $match: { companyId: objectIdCompanyId }
                },
                {
                    $lookup: {
                        from: 'paymenthistories', // Ensure this matches your collection name
                        localField: '_id',
                        foreignField: 'customerId',
                        as: 'payments'
                    }
                },
                {
                    $addFields: {
                        totalPaid: { $sum: '$payments.paid' },
                        totalCredit: { $sum: '$payments.credit' }
                    }
                },
                {
                    $project: {
                        _id: 0,
                        customerId: '$_id',
                        name: '$name',
                        phone: '$phone',
                        balance: { $subtract: ['$totalPaid', '$totalCredit'] }
                    }
                }
            ]);
    
          

  
    res.status(200).json(customers);

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

// Fetch a specific customer by ID
exports.getCustomerById = async (req, res) => {
  try {
    const customer = await Customer.findById(req.params.id).populate('companyId');
    if (!customer) return res.status(404).json({ message: 'Customer not found' });
    res.status(200).json(customer);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

// Create a new customer
exports.createCustomer = async (req, res) => {
  try {
   
    const { companyId, name, customerType, phone, status } = req.body;

    const customer = new Customer({
      companyId,
      name,
      customerType,
    
      phone,
      status
    });

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

// Update an existing customer
exports.updateCustomer = async (req, res) => {
  try {
    const { name, customerType, phone, status } = req.body;
    const customer = await Customer.findById(req.params.id);

    if (!customer) return res.status(404).json({ message: 'Customer not found' });

    customer.name = name || customer.name;
    customer.customerType = customerType || customer.customerType;
   
    customer.status = status || customer.status;
    customer.phone = phone|| customer.phone;

    await customer.save();
    res.status(200).json(customer);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

// Delete a customer
exports.deleteCustomer = async (req, res) => {
  try {
    const customer = await Customer.findById(req.params.id);

    if (!customer) return res.status(404).json({ message: 'Customer not found' });

    await customer.remove();
    res.status(200).json({ message: 'Customer deleted successfully' });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};


exports.getCustomersList = async (req, res) => {
  try {
    const companyId=req.query.companyId;

   
   
            const objectIdCompanyId = new mongoose.Types.ObjectId(companyId);
           // console.log('ObjectId:', objectIdCompanyId); // Log the ObjectId to verify
    
            const  customers = await Customer.find({ companyId: objectIdCompanyId });

  // console.log("Bbbb", customers);
    res.status(200).json(customers);

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