import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateOrderSchema } from '@server/validators/orders.validator';
import { getOrder, updateOrderStatus, updateOrderDetails, cancelOrder, deleteOrder } from '@server/services/orders.service';

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

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateOrderSchema, async (req, ctx: RouteContext) => {
      const { id } = await ctx.params;
      const body = req.parsedBody;

      const fullUpdateFields = new Set(['items', 'customer_name', 'customer_phone', 'delivery_type', 'delivery_address', 'table_number', 'special_instructions']);
      const isFullUpdate = Object.keys(body).some(k => fullUpdateFields.has(k));

      if (isFullUpdate) {
        const order = await updateOrderDetails(id, req.session.restaurantId!, body as Record<string, unknown>);
        return NextResponse.json({ order });
      }

      const { status, modification_note } = body;

      if (!status) {
        return NextResponse.json({ error: 'status is required' }, { status: 400 });
      }

      if (status === 'cancelled') {
        const order = await cancelOrder(id, req.session.restaurantId!, modification_note);
        return NextResponse.json({ order });
      }

      const order = await updateOrderStatus(id, req.session.restaurantId!, status, modification_note);
      return NextResponse.json({ order });
    })
  )
);

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