import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import {
  getRestaurantForWidget,
  getWidgetSettings,
  createWidgetConversation,
  signWidgetToken,
} from '@server/services/widget.service';
import { withWidgetCors, widgetOptionsResponse } from '../_cors';

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

export const POST = withWidgetCors(
  withErrorHandler(async (req: Request) => {
    const body = await req.json().catch(() => ({}));
    const { restaurantId, customerName } = body as { restaurantId?: string; customerName?: string };

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

    const restaurant = await getRestaurantForWidget(restaurantId);
    if (!restaurant) {
      return NextResponse.json({ error: 'Restaurant not found or inactive' }, { status: 404 });
    }

    const settings = await getWidgetSettings(restaurantId);
    if (!settings?.is_enabled) {
      return NextResponse.json({ error: 'Chat widget is not enabled for this restaurant' }, { status: 403 });
    }

    const conversation = await createWidgetConversation(
      restaurantId,
      customerName || 'Website Visitor',
      settings.agent_id ?? null
    );
    const sessionToken = signWidgetToken(restaurantId, conversation.id);

    return NextResponse.json({
      sessionToken,
      conversationId: conversation.id,
      restaurant: {
        id: restaurant.id,
        name: restaurant.name,
        logo_url: restaurant.logo_url,
      },
      settings,
    });
  })
);
