import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { ValidationError } from '@server/errors';
import { previewStorefrontCoupon } from '@server/services/storefront.service';

const previewSchema = z.object({
  code: z.string().trim().min(1).max(40),
  delivery_type: z.enum(['dine-in', 'takeaway', 'delivery']),
  items: z.array(z.object({
    menu_item_id: z.string().uuid(),
    quantity: z.number().int().min(1).max(99),
  })).min(1).max(50),
});

export const POST = withErrorHandler(async (req: Request, ctx: RouteContext) => {
  const { restaurantSlug, branchSlug } = await ctx.params;
  const body = await req.json().catch(() => null);
  if (!body) throw new ValidationError('Invalid request body');
  const parsed = previewSchema.safeParse(body);
  if (!parsed.success) {
    throw new ValidationError('Invalid coupon payload', parsed.error.flatten().fieldErrors as Record<string, string[]>);
  }
  const result = await previewStorefrontCoupon(restaurantSlug, branchSlug, parsed.data);
  return NextResponse.json(result);
});
