import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ValidationError } from '@server/errors';
import { createMenuItemSchema } from '@server/validators/menu.validator';
import { createItem } from '@server/services/menu.service';
import { requirePlanFeature } from '@server/utils/features';

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    await requirePlanFeature(restaurantId!, 'bulk_upload');

    let body: Awaited<ReturnType<typeof req.json>>;
    try {
      body = await req.json();
    } catch {
      throw new ValidationError('Request body must be valid JSON');
    }
    const parsed = createMenuItemSchema.parse(body);
    const item = await createItem(restaurantId!, parsed);
    return NextResponse.json({ item }, { status: 201 });
  })
);
