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

router.get('/', async (req, res) => {
  try {
    const { level1, active } = req.query;
    let sql = 'SELECT * FROM expense_categories WHERE 1=1';
    const params = [];
    if (level1) {
      params.push(level1);
      sql += ` AND category_level1 = $${params.length}`;
    }
    if (active !== undefined) {
      params.push(active === 'true');
      sql += ` AND is_active = $${params.length}`;
    }
    sql += ' ORDER BY category_level1, sort_order';
    const result = await db.query(sql, params);
    res.json({ success: true, data: result.rows });
  } catch (error) {
    console.error('获取分类失败:', error);
    res.status(500).json({ success: false, message: '获取分类失败' });
  }
});

router.get('/grouped', async (req, res) => {
  try {
    const result = await db.query('SELECT * FROM expense_categories WHERE is_active = true ORDER BY category_level1, sort_order');
    const grouped = {
      income: [],
      project: [],
      company: []
    };
    result.rows.forEach(row => {
      if (grouped[row.category_level1]) {
        grouped[row.category_level1].push({
          value: row.category_level2,
          label: row.label,
          description: row.description
        });
      }
    });
    res.json({ success: true, data: grouped });
  } catch (error) {
    console.error('获取分组分类失败:', error);
    res.status(500).json({ success: false, message: '获取分组分类失败' });
  }
});

router.post('/', authenticate, async (req, res) => {
  try {
    if (req.user.role !== 'admin') {
      return res.status(403).json({ success: false, message: '无权限操作' });
    }
    const { category_level1, category_level2, label, description, sort_order } = req.body;
    if (!category_level1 || !category_level2 || !label) {
      return res.status(400).json({ success: false, message: '缺少必填字段' });
    }
    const result = await db.query(
      `INSERT INTO expense_categories (category_level1, category_level2, label, description, sort_order)
       VALUES ($1, $2, $3, $4, $5) RETURNING *`,
      [category_level1, category_level2, label, description, sort_order || 0]
    );
    res.json({ success: true, data: result.rows[0] });
  } catch (error) {
    console.error('创建分类失败:', error);
    if (error.code === '23505') {
      return res.status(400).json({ success: false, message: '分类已存在' });
    }
    res.status(500).json({ success: false, message: '创建分类失败' });
  }
});

router.put('/:id', authenticate, async (req, res) => {
  try {
    if (req.user.role !== 'admin') {
      return res.status(403).json({ success: false, message: '无权限操作' });
    }
    const { id } = req.params;
    const { category_level1, category_level2, label, description, sort_order, is_active } = req.body;
    const result = await db.query(
      `UPDATE expense_categories SET
        category_level1 = COALESCE($1, category_level1),
        category_level2 = COALESCE($2, category_level2),
        label = COALESCE($3, label),
        description = COALESCE($4, description),
        sort_order = COALESCE($5, sort_order),
        is_active = COALESCE($6, is_active),
        updated_at = CURRENT_TIMESTAMP
       WHERE id = $7 RETURNING *`,
      [category_level1, category_level2, label, description, sort_order, is_active, id]
    );
    if (result.rows.length === 0) {
      return res.status(404).json({ success: false, message: '分类不存在' });
    }
    res.json({ success: true, data: result.rows[0] });
  } catch (error) {
    console.error('更新分类失败:', error);
    res.status(500).json({ success: false, message: '更新分类失败' });
  }
});

router.delete('/:id', authenticate, async (req, res) => {
  try {
    if (req.user.role !== 'admin') {
      return res.status(403).json({ success: false, message: '无权限操作' });
    }
    const { id } = req.params;
    const result = await db.query('DELETE FROM expense_categories WHERE id = $1 RETURNING *', [id]);
    if (result.rows.length === 0) {
      return res.status(404).json({ success: false, message: '分类不存在' });
    }
    res.json({ success: true, message: '删除成功' });
  } catch (error) {
    console.error('删除分类失败:', error);
    res.status(500).json({ success: false, message: '删除分类失败' });
  }
});

module.exports = router;
