import { NextResponse } from 'next/server';
import { withV1ErrorHandler } from '@server/middleware/v1Errors';
import { withApiKey, ApiKeyRequest } from '@server/middleware/withApiKey';
import { withV1Validation } from '@server/middleware/v1Validation';
import { ParsedRequest } from '@server/middleware/withValidation';
import { RouteContext } from '@server/middleware/withErrorHandler';
import { updateMenuItemSchema, UpdateMenuItemInput } from '@server/validators/menu.validator';
import { getItem, updateItem, deleteItem } from '@server/services/menu.service';

export const GET = withV1ErrorHandler(
  withApiKey(async (req: ApiKeyRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    const item = await getItem(id, req.apiKey.restaurantId);
    return NextResponse.json({ data: item });
  }, { permission: 'menu:read' })
);

export const PATCH = withV1ErrorHandler(
  withApiKey(
    withV1Validation(updateMenuItemSchema, async (req: ParsedRequest<UpdateMenuItemInput>, ctx: RouteContext) => {
      const apiReq = req as ParsedRequest<UpdateMenuItemInput> & ApiKeyRequest;
      const { id } = await ctx.params;
      const updated = await updateItem(
        id,
        apiReq.apiKey.restaurantId,
        req.parsedBody as unknown as Record<string, unknown>,
      );
      return NextResponse.json({ data: updated });
    }),
    { permission: 'menu:write' }
  )
);

export const DELETE = withV1ErrorHandler(
  withApiKey(async (req: ApiKeyRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    await deleteItem(id, req.apiKey.restaurantId);
    return NextResponse.json({ data: { id, deleted: true } });
  }, { permission: 'menu:write' })
);
