import { Request, Response } from 'express';
import { ExamSubjectModel } from '../models/examSubject';

export class ExamSubjectController {
  static async getSubjects(req: Request, res: Response) {
    try {
      const subjects = await ExamSubjectModel.findAll();
      res.json({
        success: true,
        data: subjects
      });
    } catch (error: any) {
      res.status(500).json({
        success: false,
        message: error.message || '获取考试科目失败'
      });
    }
  }

  static async createSubject(req: Request, res: Response) {
    try {
      const { name, totalScore, timeLimitMinutes, typeRatios, categoryRatios } = req.body;

      const subject = await ExamSubjectModel.create({
        name,
        totalScore,
        timeLimitMinutes,
        typeRatios,
        categoryRatios
      });

      res.json({
        success: true,
        data: subject
      });
    } catch (error: any) {
      res.status(400).json({
        success: false,
        message: error.message || '新增考试科目失败'
      });
    }
  }

  static async updateSubject(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const { name, totalScore, timeLimitMinutes, typeRatios, categoryRatios } = req.body;

      const subject = await ExamSubjectModel.update(id, {
        name,
        totalScore,
        timeLimitMinutes,
        typeRatios,
        categoryRatios
      });

      res.json({
        success: true,
        data: subject
      });
    } catch (error: any) {
      const message = error.message || '更新考试科目失败';
      res.status(message === '科目不存在' ? 404 : 400).json({
        success: false,
        message
      });
    }
  }

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

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