const express = require('express');
const db = require('../db');
const { authenticate, requireAdmin } = require('../middleware/auth');

const router = express.Router();

router.get('/', async (req, res) => {
  try {
    const { product_id, project_id, record_type } = req.query;
    let query = `
      SELECT ir.*, p.name as product_name, prj.name as project_name 
      FROM inventory_records ir
      LEFT JOIN products p ON ir.product_id = p.id
      LEFT JOIN projects prj ON ir.project_id = prj.id
    `;
    const params = [];
    const conditions = [];
    
    if (product_id) {
      conditions.push('ir.product_id = $1');
      params.push(product_id);
    }
    if (project_id) {
      conditions.push('ir.project_id = $1');
      params.push(project_id);
    }
    if (record_type) {
      conditions.push('ir.record_type = $1');
      params.push(record_type);
    }
    
    if (conditions.length > 0) {
      query += ' WHERE ' + conditions.join(' AND ');
    }
    
    query += ' ORDER BY ir.created_at DESC';
    
    const result = await db.query(query, params);
    
    res.json({
      success: true,
      data: result.rows,
      count: result.rows.length
    });
  } catch (error) {
    console.error('获取库存记录失败:', error);
    res.status(500).json({
      success: false,
      message: '获取库存记录失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

router.get('/summary', async (req, res) => {
  try {
    const result = await db.query(`
      SELECT 
        p.id as product_id,
        p.name as product_name,
        p.unit,
        SUM(CASE WHEN ir.record_type = 'in' THEN ir.quantity ELSE 0 END) as total_in,
        SUM(CASE WHEN ir.record_type = 'out' THEN ir.quantity ELSE 0 END) as total_out,
        SUM(CASE WHEN ir.record_type = 'in' THEN ir.quantity ELSE -ir.quantity END) as current_quantity
      FROM products p
      LEFT JOIN inventory_records ir ON p.id = ir.product_id
      GROUP BY p.id, p.name, p.unit
    `);
    
    res.json({
      success: true,
      data: result.rows
    });
  } catch (error) {
    console.error('获取库存汇总失败:', error);
    res.status(500).json({
      success: false,
      message: '获取库存汇总失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

router.post('/out', async (req, res) => {
  try {
    const { project_id, product_id, quantity, unit_price, total_amount, operator, remark } = req.body;
    
    const result = await db.query(`
      INSERT INTO inventory_records 
      (record_type, project_id, product_id, quantity, unit_price, total_amount, record_date, operator, remark)
      VALUES ($1, $2, $3, $4, $5, $6, CURRENT_DATE, $7, $8)
    `, ['out', project_id || null, product_id, quantity, unit_price || null, total_amount || null, operator || '系统', remark || null]);
    
    res.json({
      success: true,
      message: '出库成功',
      data: { id: (result.rows[0]?.id || result.rows?.[0]?.id) }
    });
  } catch (error) {
    console.error('出库失败:', error);
    res.status(500).json({
      success: false,
      message: '出库失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});


module.exports = router;