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 { updateOrderSchema, UpdateOrderInput } from '@server/validators/orders.validator';
import { getOrder, updateOrderStatus, updateOrderDetails } from '@server/services/orders.service';

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

export const PATCH = withV1ErrorHandler(
  withApiKey(
    withV1Validation(updateOrderSchema, async (req: ParsedRequest<UpdateOrderInput>, ctx: RouteContext) => {
      const apiReq = req as ParsedRequest<UpdateOrderInput> & ApiKeyRequest;
      const { id } = await ctx.params;
      const body = req.parsedBody as UpdateOrderInput;

      // Status-only PATCHes route through updateOrderStatus so the existing
      // webhook + loyalty side-effects fire identically to dashboard edits.
      const isStatusOnly =
        body.status !== undefined &&
        Object.keys(body).filter((k) => body[k as keyof UpdateOrderInput] !== undefined).every(
          (k) => k === 'status' || k === 'modification_note'
        );

      const updated = isStatusOnly
        ? await updateOrderStatus(id, apiReq.apiKey.restaurantId, body.status as string, body.modification_note ?? undefined)
        : await updateOrderDetails(id, apiReq.apiKey.restaurantId, body as unknown as Record<string, unknown>);

      return NextResponse.json({ data: updated });
    }),
    { permission: 'orders:write' }
  )
);
