export default defineEventHandler(async (event) => {
  const body = await readBody<{
    stripeSessionId: string;
    designId: string;
    templateId?: string;
    amount: number | string;
    currency: string;
    customerEmail?: string;
    customerDetails?: {
      name?: string | null;
      email?: string | null;
      phone?: string | null;
      address?: {
        line1?: string | null;
        line2?: string | null;
        city?: string | null;
        state?: string | null;
        postalCode?: string | null;
        country?: string | null;
      } | null;
    };
  }>(event);

  if (!body?.stripeSessionId || !body?.designId) {
    throw createError({
      statusCode: 400,
      statusMessage: "Missing required fields",
    });
  }

  const config = useRuntimeConfig();
  const backendUrl = config.public?.backendUrl;

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

  const record = {
    stripeSessionId: body.stripeSessionId,
    designId: body.designId,
    templateId: body.templateId ?? null,
    amount: body.amount.toString(),
    currency: body.currency,
    customerEmail: body.customerEmail ?? null,
    customerDetails: body.customerDetails ?? null,
  };

  console.log("[transactions] Forwarding record to backend:", record);  

  try {
    const backendResult = await $fetch("/transactions", {
      baseURL: backendUrl,
      method: "POST",
      body: record,
    });

    return {
      ok: true,
      receivedAt: new Date().toISOString(),
      backendResult,
    };
  } catch (err) {
    console.error("[transactions] Failed to forward to backend", err);
    throw createError({
      statusCode: 502,
      statusMessage:
        (err as Error)?.message ?? "Failed to save transaction to backend",
    });
  }
});
