All files / src/app/api/support/chatbot route.ts

100% Statements 57/57
80% Branches 8/10
100% Functions 1/1
100% Lines 57/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 581x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 1x 1x 1x 7x 7x 7x 8x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 3x 3x 3x 3x 8x 8x 8x 8x 8x 1x 1x  
export const dynamic = "force-dynamic";
 
/**
 * Chatbot API
 * POST /api/support/chatbot - Get chatbot response
 */
 
import { NextRequest, NextResponse } from 'next/server';
import { ChatbotMessageSchema } from "@/lib/validation/support-schemas";
import {
  generateChatbotResponse,
  getWelcomeResponse } from "@/lib/support/chatbot-utils";
import { logger } from "@/lib/logging";
import {
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse } from "@/lib/api";
import { ChatbotResponse } from "@/types/support";
 
/**
 * POST /api/support/chatbot
 * Get chatbot response (public)
 */
async function handlePost(request: NextRequest): Promise<NextResponse<ApiSuccessResponse<ChatbotResponse>>> {
  const body = await request.json();
 
  // Check if requesting welcome message
  if (body.welcome === true) {
    const welcomeResponse = getWelcomeResponse();
    return successResponse(welcomeResponse);
  }
 
  // Validate message input
  const validationResult = ChatbotMessageSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation(
      "Validation failed",
      validationResult.error.flatten().fieldErrors
    );
  }
 
  const { message } = validationResult.data;
 
  // Generate response
  const response = await generateChatbotResponse(message);
 
  logger.info("Chatbot response generated", {
    category: "API",
    messageLength: message.length,
    suggestedArticles: response.suggestedArticles?.length || 0,
    shouldEscalate: response.shouldEscalate || false});
 
  return successResponse(response);
}
 
export const POST = withErrorHandling(handlePost);