import { Request, Response, NextFunction } from 'express';
import { ChatBotService } from '../../core/ai/ChatBotService';
import { z } from 'zod';

const chatRequestSchema = z.object({
  tenantId: z.string().min(1),
  sessionId: z.string().min(1),
  userMessage: z.string().min(1),
});

const trainRequestSchema = z.object({
  tenantId: z.string().min(1),
  trainingData: z.array(z.object({
    userMessage: z.string().min(1),
    intent: z.string().min(1),
  })),
});

export class ChatBotController {
  /**
   * 处理用户消息
   */
  static async handleMessage(req: Request, res: Response, next: NextFunction) {
    try {
      const request = chatRequestSchema.parse(req.body);
      const result = await ChatBotService.handleMessage({
        tenantId: request.tenantId,
        sessionId: request.sessionId,
        userMessage: request.userMessage
      });
      res.json({ success: true, data: result });
    } catch (err: any) {
      if (err instanceof z.ZodError) {
        return res.status(400).json({ success: false, error: err.issues[0].message });
      }
      next(err);
    }
  }

  /**
   * 获取聊天历史
   */
  static async getChatHistory(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId, sessionId } = req.query;
      if (!tenantId || !sessionId) {
        return res.status(400).json({ success: false, error: 'Missing required parameters' });
      }
      const result = await ChatBotService.getChatHistory(tenantId as string, sessionId as string);
      res.json({ success: true, data: result });
    } catch (err) {
      next(err);
    }
  }

  /**
   * 训练意图模型
   */
  static async trainIntentModel(req: Request, res: Response, next: NextFunction) {
    try {
      const request = trainRequestSchema.parse(req.body);
      const result = await ChatBotService.trainIntentModel(
        request.tenantId,
        request.trainingData
      );
      res.json({ success: true, data: result });
    } catch (err: any) {
      if (err instanceof z.ZodError) {
        return res.status(400).json({ success: false, error: err.issues[0].message });
      }
      next(err);
    }
  }

  /**
   * 初始化聊天机器人服务
   */
  static async initChatBot(req: Request, res: Response, next: NextFunction) {
    try {
      await ChatBotService.initTable();
      res.json({ success: true, data: { status: 'success', message: 'ChatBot service initialized' } });
    } catch (err) {
      next(err);
    }
  }
}