const pool = require('../config/db');

async function getAll(req, res) {
  try {
    const { product_id, type, start_date, end_date, limit = 100 } = req.query;

    let query = `
      SELECT sm.*, p.name AS product_name, p.sku, u.name AS user_name
      FROM stock_movements sm
      JOIN products p ON sm.product_id = p.id
      LEFT JOIN users u ON sm.user_id = u.id
      WHERE 1=1
    `;
    const params = [];

    if (product_id) {
      query += ' AND sm.product_id = ?';
      params.push(product_id);
    }

    if (type) {
      query += ' AND sm.type = ?';
      params.push(type);
    }

    if (start_date) {
      query += ' AND sm.created_at >= ?';
      params.push(start_date);
    }

    if (end_date) {
      query += ' AND sm.created_at <= ?';
      params.push(`${end_date} 23:59:59`);
    }

    query += ' ORDER BY sm.created_at DESC LIMIT ?';
    params.push(parseInt(limit, 10));

    const [movements] = await pool.query(query, params);
    res.json({ movements });
  } catch (error) {
    console.error('Get movements error:', error);
    res.status(500).json({ message: 'Server error' });
  }
}

module.exports = { getAll };
