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

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export const GET = withErrorHandler(async (req: Request, ctx: RouteContext) => {
  const { restaurantSlug, branchSlug, orderId } = await ctx.params;
  if (!UUID_RE.test(orderId)) throw new ValidationError('Invalid order id');
  const url = new URL(req.url);
  const phoneRaw = url.searchParams.get('phone');
  if (!phoneRaw) throw new ValidationError('phone query parameter is required');
  // Match the same normalization used at create time so polling succeeds for inputs like "+1 (415) 555-1234"
  const phone = phoneRaw.replace(/[\s\-().]/g, '');
  const status = await getStorefrontOrderStatus(restaurantSlug, branchSlug, orderId, phone);
  if (!status) return NextResponse.json({ error: 'Order not found' }, { status: 404 });
  return NextResponse.json({ order: status }, { headers: { 'Cache-Control': 'no-store' } });
});
