const Sales = require('../models/sales');
const Product = require('../models/product');
const Customer = require('../models/customer');

exports.addsales = async (req, res) => {
  try {
    const { invoiceNumber, salesDate, paymentMethod, totalAmountPaid, quantitySold, productId, customerId } = req.body;

    const product = await Product.findById(productId);
    const customer = await Customer.findById(customerId);

    if (!product) return res.status(400).json({ message: 'Product selection is required' });
    if (!customer) return res.status(400).json({ message: 'Customer selection is required' });

    const existing = await Sales.findOne({ invoiceNumber });
    if (existing) {
      return res.status(409).json({ message: 'Invoice number already exists' });
    }

    const sales = await Sales.create({
      invoiceNumber,
      salesDate,
      paymentMethod,
      totalAmountPaid,
      quantitySold,
      product_FK: productId,
      customer_FK: customerId,
    });

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

exports.getsales = async (req, res) => {
  try {
    const sales = await Sales.find().populate('product_FK').populate('customer_FK').sort({ salesDate: -1 });
    res.status(200).json(sales);
  } catch (error) {
    res.status(404).json({ message: 'Sales not found' });
  }
};

exports.getsalesbyid = async (req, res) => {
  try {
    const sale = await Sales.findById(req.params.id).populate('product_FK').populate('customer_FK');
    if (!sale) {
      return res.status(404).json({ message: 'Sale not found' });
    }
    res.status(200).json(sale);
  } catch (error) {
    res.status(404).json({ message: 'Failed to fetch sale' });
  }
};

exports.updatesales = async (req, res) => {
  try {
    const { invoiceNumber, salesDate, paymentMethod, totalAmountPaid, quantitySold, productId, customerId } = req.body;
    const sale = await Sales.findById(req.params.id);
    if (!sale) return res.status(404).json({ message: 'Sale not found' });

    sale.invoiceNumber = invoiceNumber;
    sale.salesDate = salesDate;
    sale.paymentMethod = paymentMethod;
    sale.totalAmountPaid = totalAmountPaid;
    sale.quantitySold = quantitySold;
    sale.product_FK = productId;
    sale.customer_FK = customerId;

    await sale.save();

    const updatedSale = await Sales.findById(req.params.id).populate('product_FK').populate('customer_FK');
    res.status(200).json(updatedSale);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

exports.deletesales = async (req, res) => {
  try {
    const deleted = await Sales.findByIdAndDelete(req.params.id);
    if (!deleted) return res.status(404).json({ message: 'Sale not found' });
    res.status(200).json({ message: 'Sale deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
