export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig();
  const backendUrl = config.public?.backendUrl;

  if (!backendUrl) {
    throw createError({ statusCode: 500, statusMessage: "Backend URL not configured" });
  }

  const query = getQuery(event);
  const customerEmail = typeof query.customerEmail === "string" ? query.customerEmail : null;

  if (!customerEmail) {
    throw createError({ statusCode: 400, statusMessage: "Missing customerEmail" });
  }

  try {
    const result = await $fetch("/transactions", {
      baseURL: backendUrl,
      method: "GET",
      query: { customerEmail },
    });

    if (Array.isArray(result)) {
      return result;
    }

    if (result && Array.isArray((result as any).data)) {
      return (result as any).data;
    }

    if (result && Array.isArray((result as any).orders)) {
      return (result as any).orders;
    }

    return result;
  } catch (err) {
    console.error("[orders] Failed to fetch order history", err);
    throw createError({
      statusCode: 502,
      statusMessage: (err as Error)?.message ?? "Failed to load order history",
    });
  }
});
