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

// Get all bills
router.get('/', async (req, res) => {
  try {
    const bills = await Bill.find({})
      .populate('customerId', 'name phone')
      .populate('items.productId', 'name price');
    res.json(bills);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// Get single bill
router.get('/:id', async (req, res) => {
  try {
    const bill = await Bill.findById(req.params.id)
      .populate('customerId', 'name phone email')
      .populate('items.productId', 'name price category');
    
    if (!bill) {
      return res.status(404).json({ message: 'Bill not found' });
    }
    res.json(bill);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// Create bill
router.post('/', async (req, res) => {
  try {
    const bill = new Bill(req.body);
    const savedBill = await bill.save();
    
    // Update product stock
    for (const item of req.body.items) {
      await Product.findByIdAndUpdate(
        item.productId,
        { $inc: { stock: -item.qty } }
      );
    }
    
    res.status(201).json(savedBill);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

// Update bill
router.put('/:id', async (req, res) => {
  try {
    // Get the original bill to restore stock
    const originalBill = await Bill.findById(req.params.id);
    if (!originalBill) {
      return res.status(404).json({ message: 'Bill not found' });
    }
    
    // Restore original stock quantities
    for (const item of originalBill.items) {
      await Product.findByIdAndUpdate(
        item.productId,
        { $inc: { stock: item.qty } }
      );
    }
    
    // Update the bill
    const bill = await Bill.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    );
    
    // Deduct new quantities from stock
    for (const item of req.body.items) {
      await Product.findByIdAndUpdate(
        item.productId,
        { $inc: { stock: -item.qty } }
      );
    }
    
    res.json(bill);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

// Delete bill
router.delete('/:id', async (req, res) => {
  try {
    const bill = await Bill.findById(req.params.id);
    if (!bill) {
      return res.status(404).json({ message: 'Bill not found' });
    }
    
    // Restore stock quantities
    for (const item of bill.items) {
      await Product.findByIdAndUpdate(
        item.productId,
        { $inc: { stock: item.qty } }
      );
    }
    
    await Bill.findByIdAndDelete(req.params.id);
    res.json({ message: 'Bill removed' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;