import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { updateMenuItemSchema } from '@server/validators/menu.validator';
import { getItem, updateItem, deleteItem } from '@server/services/menu.service';
import { uploadImage } from '@server/utils/upload';
import { formDataToObject } from '@server/utils/formParsing';

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

export const PATCH = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const contentType = req.headers.get('content-type') || '';
    let body: any;

    if (contentType.includes('multipart/form-data')) {
      const formData = await req.formData();
      body = formDataToObject(formData);

      const image = formData.get('image') as File | null;
      if (image && image.size > 0) {
        body.image_url = await uploadImage(image);
      }
      delete body.image;
    } else {
      body = await req.json();
    }

    const { id } = await ctx.params;
    const parsed = updateMenuItemSchema.parse(body);
    const item = await updateItem(id, req.session.restaurantId!, parsed);
    return NextResponse.json({ item });
  })
);

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