import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { createMenuItemSchema } from '@server/validators/menu.validator';
import { listItems, createItem } 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) => {
    const { restaurantId, branchId } = req.session;
    const url = new URL(req.url);
    const p = url.searchParams;

    const result = await listItems({
      restaurantId: restaurantId!,
      branchId: p.get('branch_id') ?? branchId ?? undefined,
      categoryId: p.get('category_id') ?? undefined,
      available: p.has('available') ? p.get('available') === 'true' : undefined,
      search: p.get('search') ?? undefined,
      page: parseInt(p.get('page') ?? '1', 10),
      limit: parseInt(p.get('limit') ?? '50', 10),
    });

    return NextResponse.json(result);
  })
);

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    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 parsed = createMenuItemSchema.parse(body);
    const item = await createItem(req.session.restaurantId!, parsed);
    return NextResponse.json({ item }, { status: 201 });
  })
);
