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 { createCategorySchema } from '@server/validators/menu.validator';
import { listCategories, createCategory } from '@server/services/menu.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    const url = new URL(req.url);
    const p = url.searchParams;
    const categories = await listCategories(restaurantId!, p.get('branch_id') ?? branchId ?? undefined);
    return NextResponse.json({ categories });
  })
);

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