import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { verifyWidgetToken, getWidgetConversation } from '@server/services/widget.service';
import { withWidgetCors, widgetOptionsResponse } from '../../_cors';

export async function OPTIONS() { return widgetOptionsResponse(); }

export const GET = withWidgetCors(
  withErrorHandler(async (req: Request, ctx: RouteContext) => {
    const params = await ctx.params;
    const sessionId = params['sessionId'];

    if (!sessionId) {
      return NextResponse.json({ error: 'sessionId is required' }, { status: 400 });
    }

    const session = verifyWidgetToken(decodeURIComponent(sessionId));
    if (!session) {
      return NextResponse.json({ error: 'Invalid or expired session token' }, { status: 401 });
    }

    const { restaurantId, conversationId } = session;
    const conversation = await getWidgetConversation(conversationId, restaurantId);

    if (!conversation) {
      return NextResponse.json({ error: 'Conversation not found' }, { status: 404 });
    }

    const messages = Array.isArray(conversation.messages) ? conversation.messages : [];

    return NextResponse.json({
      conversationId,
      messages,
      status: conversation.status,
    });
  })
);
