import { randomUUID } from "crypto";

export type MindmapRouteMeta = {
  requestId: string;
  traceId: string;
  workspaceId: string | null;
  documentId: string;
  pageId: string;
  mindmapId: string;
  attachmentId: string;
  ownerUserId: string;
  source: "convex";
};

function readHeaderValue(headerList: Headers, ...candidates: string[]): string | null {
  for (const candidate of candidates) {
    const value = headerList.get(candidate);
    if (typeof value === "string" && value.trim()) {
      return value.trim();
    }
  }
  return null;
}

function makeFallbackId(prefix: string): string {
  return `${prefix}_${randomUUID()}`;
}

export function buildMindmapRouteMeta(
  request: Request,
  input: {
    workspaceId?: string | null;
    documentId: string;
    mindmapId: string;
    ownerUserId: string;
  },
): MindmapRouteMeta {
  const requestId =
    readHeaderValue(request.headers, "x-request-id", "x-mnote-request-id") ??
    makeFallbackId("req");
  const traceId =
    readHeaderValue(request.headers, "x-trace-id", "x-mnote-trace-id", "x-request-id") ??
    makeFallbackId("trace");

  return {
    requestId,
    traceId,
    workspaceId: input.workspaceId?.trim() || null,
    documentId: input.documentId,
    pageId: input.documentId,
    mindmapId: input.mindmapId,
    attachmentId: input.mindmapId,
    ownerUserId: input.ownerUserId,
    source: "convex",
  };
}
