export default defineEventHandler(async (event) => {
  const body = await readBody<{
    designId: string;
    templateId: string;
    ownerEmail?: string | null;
    ownerId?: string | null;
    previewUrl?: string | null;
    productionUrl?: string | null;
    canvasJson: unknown;
    metadata?: Record<string, unknown>;
  }>(event);

  if (!body?.designId || !body?.templateId || body.canvasJson === undefined) {
    throw createError({
      statusCode: 400,
      statusMessage: "Missing required design fields",
    });
  }

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

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

  // Extract the authorization token from the incoming request
  const authHeader = getHeader(event, "authorization");

  const payload = {
    designId: body.designId,
    templateId: body.templateId,
    ownerEmail: body.ownerEmail ?? null,
    ownerId: body.ownerId ?? null,
    previewUrl: body.previewUrl ?? null,
    productionUrl: body.productionUrl ?? null,
    canvasJson: body.canvasJson,
    metadata: body.metadata ?? {},
  };

  try {
    const result = await $fetch("/designs", {
      baseURL: backendUrl,
      method: "POST",
      headers: authHeader ? { Authorization: authHeader } : {},
      body: payload,
    });

    return {
      ok: true,
      result,
    };
  } catch (err) {
    console.error("[designs] Failed to forward design payload", err);
    throw createError({
      statusCode: 502,
      statusMessage: (err as Error)?.message ?? "Failed to persist design",
    });
  }
});
