import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { getWidgetSettings, getChatAgentsForRestaurant } from '@server/services/widget.service';

/**
 * Authenticated dashboard read of widget settings.
 * Enforces chat_widget read permission for staff members.
 * The public GET at /api/widget/settings remains unauthenticated for the embed script.
 */
export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    if (!restaurantId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    await requireSection(req, 'chat_widget', 'read');
    const url = new URL(req.url);
    const includeAgents = url.searchParams.get('includeAgents') === 'true';
    const [settings, agents] = await Promise.all([
      getWidgetSettings(restaurantId),
      includeAgents ? getChatAgentsForRestaurant(restaurantId) : Promise.resolve(undefined),
    ]);
    return NextResponse.json({ settings, ...(agents !== undefined ? { agents } : {}) });
  })
);
