const { query } = require('../config/database')

async function getCategories(ctx) {
  const categories = await query('SELECT * FROM categories ORDER BY sort_order ASC')
  ctx.body = {
    code: 200,
    data: categories
  }
}

async function getCategoryById(ctx) {
  const categoryId = parseInt(ctx.params.id)
  const categories = await query('SELECT * FROM categories WHERE id = ?', [categoryId])
  
  if (categories.length > 0) {
    ctx.body = {
      code: 200,
      data: categories[0]
    }
  } else {
    ctx.body = {
      code: 404,
      message: '分类不存在'
    }
  }
}

async function createCategory(ctx) {
  const { name, icon, sortOrder = 0 } = ctx.request.body
  
  if (!name) {
    ctx.body = {
      code: 400,
      message: '请输入分类名称'
    }
    return
  }
  
  const result = await query(
    'INSERT INTO categories (name, icon, sort_order) VALUES (?, ?, ?)',
    [name, icon || '', parseInt(sortOrder)]
  )
  
  ctx.body = {
    code: 200,
    message: '添加成功',
    data: { id: result.insertId, name, icon, sort_order: sortOrder }
  }
}

async function updateCategory(ctx) {
  const categoryId = parseInt(ctx.params.id)
  const { name, icon, sortOrder, isShow } = ctx.request.body
  
  if (!name) {
    ctx.body = {
      code: 400,
      message: '请输入分类名称'
    }
    return
  }
  
  const result = await query(
    'UPDATE categories SET name = ?, icon = ?, sort_order = ?, is_show = ? WHERE id = ?',
    [name, icon || '', parseInt(sortOrder) || 0, parseInt(isShow) || 1, categoryId]
  )
  
  if (result.affectedRows > 0) {
    ctx.body = {
      code: 200,
      message: '更新成功'
    }
  } else {
    ctx.body = {
      code: 404,
      message: '分类不存在'
    }
  }
}

async function deleteCategory(ctx) {
  const categoryId = parseInt(ctx.params.id)
  
  try {
    const result = await query('DELETE FROM categories WHERE id = ?', [categoryId])
    if (result.affectedRows > 0) {
      ctx.body = {
        code: 200,
        message: '删除成功'
      }
    } else {
      ctx.body = {
        code: 404,
        message: '分类不存在'
      }
    }
  } catch (error) {
    console.error('删除分类失败:', error)
    ctx.body = {
      code: 500,
      message: '删除失败，该分类下可能存在商品'
    }
  }
}

module.exports = {
  getCategories,
  getCategoryById,
  createCategory,
  updateCategory,
  deleteCategory
}