import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import {
  getWidgetSettings,
  upsertWidgetSettings,
  getRestaurantForWidget,
  getChatAgentsForRestaurant,
} from '@server/services/widget.service';
import { withWidgetCors, widgetOptionsResponse, addWidgetCors } from '../_cors';

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

export const GET = withWidgetCors(
  withErrorHandler(async (req: Request) => {
    const url = new URL(req.url);
    const restaurantId = url.searchParams.get('restaurantId');
    const includeAgents = url.searchParams.get('includeAgents') === 'true';

    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' }, { status: 404 });
    }

    const [settings, agents] = await Promise.all([
      getWidgetSettings(restaurantId),
      includeAgents ? getChatAgentsForRestaurant(restaurantId) : Promise.resolve(undefined),
    ]);

    return NextResponse.json({ settings, restaurant, ...(agents !== undefined ? { agents } : {}) });
  })
);

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    if (!restaurantId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    await requireSection(req, 'chat_widget', 'update');
    const body = await req.json().catch(() => ({}));
    const settings = await upsertWidgetSettings(restaurantId, body);
    return addWidgetCors(NextResponse.json({ settings }));
  })
);

