import { Request, Response } from 'express';
import { QuestionCategoryModel } from '../models/questionCategory';

export class QuestionCategoryController {
  static async getCategories(req: Request, res: Response) {
    try {
      const categories = await QuestionCategoryModel.findAllWithQuestionCounts();
      res.json({
        success: true,
        data: categories
      });
    } catch (error: any) {
      res.status(500).json({
        success: false,
        message: error.message || '获取题目类别失败'
      });
    }
  }

  static async createCategory(req: Request, res: Response) {
    try {
      const { name } = req.body;
      if (!name || typeof name !== 'string') {
        return res.status(400).json({
          success: false,
          message: '类别名称不能为空'
        });
      }

      const category = await QuestionCategoryModel.create(name);
      res.json({
        success: true,
        data: category
      });
    } catch (error: any) {
      res.status(400).json({
        success: false,
        message: error.message || '新增题目类别失败'
      });
    }
  }

  static async updateCategory(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const { name } = req.body;

      if (!name || typeof name !== 'string') {
        return res.status(400).json({
          success: false,
          message: '类别名称不能为空'
        });
      }

      const category = await QuestionCategoryModel.update(id, name);
      res.json({
        success: true,
        data: category
      });
    } catch (error: any) {
      const message = error.message || '更新题目类别失败';
      res.status(message === '类别不存在' ? 404 : 400).json({
        success: false,
        message
      });
    }
  }

  static async deleteCategory(req: Request, res: Response) {
    try {
      const { id } = req.params;
      await QuestionCategoryModel.delete(id);

      res.json({
        success: true,
        message: '删除成功'
      });
    } catch (error: any) {
      const message = error.message || '删除题目类别失败';
      res.status(message === '类别不存在' ? 404 : 400).json({
        success: false,
        message
      });
    }
  }
}
