import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createModifierGroupSchema } from '@server/validators/menu-modifiers.validator';
import { listModifierGroups, createModifierGroup } from '@server/services/menu-modifiers.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    const url = new URL(req.url);
    const itemId = url.searchParams.get('item_id') ?? undefined;
    const groups = await listModifierGroups(restaurantId!, itemId);
    return NextResponse.json({ groups });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createModifierGroupSchema, async (req) => {
      const group = await createModifierGroup(req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ group }, { status: 201 });
    })
  )
);
