const express = require('express');
const db = require('../db');
const router = express.Router();

router.get('/tree', async (req, res) => {
  try {
    const result = await db.query('SELECT * FROM product_categories ORDER BY id');
    const buildTree = (categories, parentId = null) => {
      return categories
        .filter(cat => cat.parent_id === parentId)
        .map(cat => ({ ...cat, children: buildTree(categories, cat.id) }));
    };
    res.json({ success: true, data: buildTree(result.rows) });
  } catch (error) {
    console.error('获取分类树失败:', error);
    res.status(500).json({ success: false, message: '获取分类树失败' });
  }
});

router.get('/', async (req, res) => {
  try {
    const { level } = req.query;
    let query = 'SELECT * FROM product_categories';
    const params = [];
    if (level === '1') {
      query += ' WHERE parent_id IS NULL';
    } else if (level === '2') {
      query += ' WHERE parent_id IS NOT NULL';
    }
    query += ' ORDER BY id';
    const result = await db.query(query, params);
    res.json({ success: true, data: result.rows });
  } catch (error) {
    console.error('获取分类失败:', error);
    res.status(500).json({ success: false, message: '获取分类失败' });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const result = await db.query('SELECT * FROM product_categories WHERE id = $1', [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.post('/', async (req, res) => {
  try {
    const { name, parent_id } = req.body;
    if (!name) {
      return res.status(400).json({ success: false, message: '分类名称不能为空' });
    }
    const result = await db.query(
      'INSERT INTO product_categories (name, parent_id) VALUES ($1, $2) RETURNING *',
      [name, parent_id || null]
    );
    res.json({ success: true, data: result.rows[0], message: '创建成功' });
  } catch (error) {
    console.error('创建分类失败:', error);
    res.status(500).json({ success: false, message: '创建分类失败' });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, parent_id } = req.body;
    const updates = [];
    const params = [];
    let i = 1;
    if (name !== undefined) { updates.push(`name = $${i++}`); params.push(name); }
    if (parent_id !== undefined) { updates.push(`parent_id = $${i++}`); params.push(parent_id || null); }
    if (updates.length === 0) {
      return res.status(400).json({ success: false, message: '没有提供更新数据' });
    }
    updates.push(`updated_at = CURRENT_TIMESTAMP`);
    params.push(id);
    const result = await db.query(`UPDATE product_categories SET ${updates.join(', ')} WHERE id = $${i} RETURNING *`, params);
    if (result.rows.length === 0) {
      return res.status(404).json({ success: false, message: '分类不存在' });
    }
    res.json({ success: true, data: result.rows[0], message: '更新成功' });
  } catch (error) {
    console.error('更新分类失败:', error);
    res.status(500).json({ success: false, message: '更新分类失败' });
  }
});

router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const result = await db.query('DELETE FROM product_categories WHERE id = $1 RETURNING id', [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;
