import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateCategorySchema } from '@server/validators/menu.validator';
import { getCategory, updateCategory, deleteCategory } from '@server/services/menu.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    const category = await getCategory(id, req.session.restaurantId!);
    return NextResponse.json({ category });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateCategorySchema, async (req, ctx: RouteContext) => {
      const { id } = await ctx.params;
      const category = await updateCategory(
        id,
        req.session.restaurantId!,
        req.parsedBody as Record<string, unknown>,
        { userId: req.session.userId, email: req.session.email },
      );
      return NextResponse.json({ category });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    await deleteCategory(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
