
/**
 * Chatbot Message API Endpoint
 * Handles user messages and returns AI-powered responses
 */

import { NextRequest, NextResponse } from 'next/server';
import { 
  processChatMessage, 
  updateSession, 
  getSession,
  type ChatMessage 
} from '@/lib/chatbot-engine';
import { errorLogger } from '@/lib/error-logger';
import { perfMonitor } from '@/lib/performance';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(req: NextRequest) {
  const stopTimer = perfMonitor.start('chatbot-message');
  
  try {
    const body = await req.json();
    const { sessionId, message } = body;

    if (!sessionId || !message) {
      return NextResponse.json(
        { error: 'Missing sessionId or message' },
        { status: 400 }
      );
    }

    // Get or create session
    const session = getSession(sessionId);

    // Add user message to session
    const userMessage: ChatMessage = {
      role: 'USER',
      content: message,
      timestamp: new Date(),
    };
    updateSession(sessionId, userMessage);

    // Process message with chatbot engine
    const response = await processChatMessage(message, session);

    // Add bot response to session
    const botMessage: ChatMessage = {
      role: 'ASSISTANT',
      content: response.text,
      timestamp: new Date(),
      intent: response.intent,
      sentiment: response.sentiment,
    };
    updateSession(sessionId, botMessage);

    // Log if human escalation is needed
    if (response.requiresHumanEscalation) {
      errorLogger.log(
        `Human escalation needed for session ${sessionId}`,
        'chatbot-escalation',
        'medium',
        {
          message,
          intent: response.intent,
          sentiment: response.sentiment,
        }
      );
    }

    stopTimer();

    return NextResponse.json({
      success: true,
      response: {
        text: response.text,
        options: response.options,
        fields: response.fields,
      },
      metadata: {
        intent: response.intent,
        sentiment: response.sentiment,
        confidence: response.confidence,
        requiresEscalation: response.requiresHumanEscalation,
      },
    });
  } catch (error) {
    stopTimer();
    errorLogger.log(error as Error, 'chatbot-message-api', 'high');
    
    return NextResponse.json(
      { 
        error: 'Failed to process message',
        response: {
          text: "I'm having trouble processing your message right now. Please try again in a moment.",
        },
      },
      { status: 500 }
    );
  }
}
