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;
      // FormData carries arrays/objects as JSON strings — re-hydrate the
      // ones the validator expects as native arrays before parsing.
      for (const k of ['schedule', 'modifiers', 'dietary_tags']) {
        if (typeof body[k] === 'string') {
          try { body[k] = JSON.parse(body[k]); } catch { /* leave as-is, validator will reject */ }
        }
      }
    } else {
      body = await req.json();
    }

    const { id } = await ctx.params;
    const parsed = updateMenuItemSchema.parse(body);
    const item = await updateItem(id, req.session.restaurantId!, parsed, {
      userId: req.session.userId,
      email: req.session.email,
    });
    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 });
  })
);
