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.status(200).json({
      status: 'success',
      message: '获取分类树成功',
      data: categories
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '获取分类树失败',
      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({ 
        status: 'error',
        message: '品类不存在',
        error: '品类不存在' 
      });
    }
    res.status(200).json({
      status: 'success',
      message: '获取品类详情成功',
      data: category
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '获取品类详情失败',
      error: error.message 
    });
  }
});

// 添加新品类
router.post('/add', async (req, res) => {
  try {
    const category = await Category.create(req.body);
    res.status(201).json({
      status: 'success',
      message: '品类创建成功',
      data: category
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '品类创建失败',
      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({ 
        status: 'error',
        message: '品类不存在',
        error: '品类不存在' 
      });
    }
    await category.update(req.body);
    res.status(200).json({
      status: 'success',
      message: '品类更新成功',
      data: category
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '品类更新失败',
      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({ 
        status: 'error',
        message: '品类不存在',
        error: '品类不存在' 
      });
    }
    await category.destroy();
    res.status(200).json({ 
      status: 'success',
      message: '品类删除成功' 
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error',
      message: '品类删除失败',
      error: error.message 
    });
  }
});

module.exports = router;