
/**
 * Chatbot Feedback API Endpoint
 * Handles user feedback for chatbot responses
 */

import { NextRequest, NextResponse } from 'next/server';
import { learnFromFeedback, getSession } from '@/lib/chatbot-engine';
import { errorLogger } from '@/lib/error-logger';
import { prisma } from '@/lib/db';

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

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { sessionId, messageId, feedback } = body;

    if (!sessionId || !messageId || !feedback) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    if (!['POSITIVE', 'NEGATIVE', 'NEUTRAL'].includes(feedback)) {
      return NextResponse.json(
        { error: 'Invalid feedback value' },
        { status: 400 }
      );
    }

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

    // Find the message in session history
    const botMessage = session.messages.find((msg, idx) => {
      return msg.role === 'ASSISTANT' && `bot-${msg.timestamp.getTime()}` === messageId;
    });

    if (botMessage && botMessage.intent) {
      // Learn from feedback
      const previousUserMessage = session.messages[session.messages.indexOf(botMessage) - 1];
      if (previousUserMessage && previousUserMessage.role === 'USER') {
        learnFromFeedback(previousUserMessage.content, botMessage.intent, feedback);
      }
    }

    // Store feedback in database
    try {
      await prisma.chatbotFeedback.create({
        data: {
          sessionId,
          messageId,
          feedback,
          timestamp: new Date(),
        },
      });
    } catch (dbError) {
      // If table doesn't exist, just log it (non-critical)
      console.log('Chatbot feedback table not yet created, skipping DB save');
    }

    return NextResponse.json({
      success: true,
      message: 'Feedback recorded',
    });
  } catch (error) {
    errorLogger.log(error as Error, 'chatbot-feedback-api', 'medium');
    
    return NextResponse.json(
      { error: 'Failed to record feedback' },
      { status: 500 }
    );
  }
}
