const express = require('express');
const router = express.Router();
const { Category } = require('../models');

// 获取所有顶级品类及其子类
router.get('/tree', async (req, res) => {
  try {
    const categories = await Category.findAll({
      where: { level: 1 },
      include: [{
        model: Category,
        as: 'children'
      }],
      order: [
        ['order', 'ASC'],
        [{ model: Category, as: 'children' }, 'order', 'ASC']
      ]
    });
    res.json(categories);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 根据ID获取品类及其所有子类
router.get('/:id', async (req, res) => {
  try {
    const category = await Category.findByPk(req.params.id, {
      include: [{
        model: Category,
        as: 'children'
      }]
    });
    if (!category) {
      return res.status(404).json({ error: '品类不存在' });
    }
    res.json(category);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 添加新品类
router.post('/', async (req, res) => {
  try {
    const category = await Category.create(req.body);
    res.status(201).json(category);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 更新品类
router.put('/:id', async (req, res) => {
  try {
    const category = await Category.findByPk(req.params.id);
    if (!category) {
      return res.status(404).json({ error: '品类不存在' });
    }
    await category.update(req.body);
    res.json(category);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除品类（会级联删除子类）
router.delete('/:id', async (req, res) => {
  try {
    const category = await Category.findByPk(req.params.id);
    if (!category) {
      return res.status(404).json({ error: '品类不存在' });
    }
    await category.destroy();
    res.status(204).send();
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;