const express = require('express');
const pool = require('../config/db');
const authMiddleware = require('../middleware/auth');

const router = express.Router();
router.use(authMiddleware);

router.get('/', async (req, res) => {
  try {
    const [sales] = await pool.query(`
      SELECT s.sale_id, s.quantity, s.unit_price, s.total_price, s.sale_date,
             c.fullname AS customer_name, c.customer_id,
             p.product_name, p.product_id
      FROM sales s
      JOIN customers c ON s.customer_id = c.customer_id
      JOIN products p ON s.product_id = p.product_id
      ORDER BY s.sale_date DESC
    `);
    res.json(sales);
  } catch (error) {
    console.error('Get sales error:', error);
    res.status(500).json({ message: 'Failed to fetch sales.' });
  }
});

router.post('/', async (req, res) => {
  const connection = await pool.getConnection();
  try {
    const { customer_id, product_id, quantity } = req.body;
    if (!customer_id || !product_id || !quantity || quantity < 1) {
      return res.status(400).json({ message: 'Customer, product, and valid quantity are required.' });
    }

    await connection.beginTransaction();

    const [products] = await connection.query('SELECT * FROM products WHERE product_id = ? FOR UPDATE', [product_id]);
    if (products.length === 0) {
      await connection.rollback();
      return res.status(404).json({ message: 'Product not found.' });
    }

    const product = products[0];
    if (product.quantity < quantity) {
      await connection.rollback();
      return res.status(400).json({ message: `Insufficient stock. Available: ${product.quantity}` });
    }

    const [customers] = await connection.query('SELECT * FROM customers WHERE customer_id = ?', [customer_id]);
    if (customers.length === 0) {
      await connection.rollback();
      return res.status(404).json({ message: 'Customer not found.' });
    }

    const unit_price = parseFloat(product.price);
    const total_price = unit_price * quantity;

    const [result] = await connection.query(
      'INSERT INTO sales (customer_id, product_id, quantity, unit_price, total_price) VALUES (?, ?, ?, ?, ?)',
      [customer_id, product_id, quantity, unit_price, total_price]
    );

    await connection.query(
      'UPDATE products SET quantity = quantity - ? WHERE product_id = ?',
      [quantity, product_id]
    );

    await connection.commit();

    const [newSale] = await pool.query(`
      SELECT s.sale_id, s.quantity, s.unit_price, s.total_price, s.sale_date,
             c.fullname AS customer_name, p.product_name
      FROM sales s
      JOIN customers c ON s.customer_id = c.customer_id
      JOIN products p ON s.product_id = p.product_id
      WHERE s.sale_id = ?
    `, [result.insertId]);

    res.status(201).json(newSale[0]);
  } catch (error) {
    await connection.rollback();
    console.error('Create sale error:', error);
    res.status(500).json({ message: 'Failed to record sale.' });
  } finally {
    connection.release();
  }
});

module.exports = router;
