import { headers } from "next/headers";
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server";
import { isDevAuthEnabled } from "@/lib/auth/devUser";
import { getAuthContext } from "@/lib/auth/authContext";

function copyHeaderIfPresent(target: Headers, source: Headers, name: string) {
  const value = source.get(name);
  if (value) {
    target.set(name, value);
  }
}

export async function buildForwardHeaders(request?: Request): Promise<Headers> {
  const source = request?.headers ?? new Headers(await headers());
  const forwarded = new Headers();

  copyHeaderIfPresent(forwarded, source, "cookie");
  copyHeaderIfPresent(forwarded, source, "authorization");
  copyHeaderIfPresent(forwarded, source, "x-request-id");
  copyHeaderIfPresent(forwarded, source, "x-trace-id");
  copyHeaderIfPresent(forwarded, source, "x-session-id");
  copyHeaderIfPresent(forwarded, source, "x-mnote-workspace-id");
  copyHeaderIfPresent(forwarded, source, "x-mnote-source-channel");
  copyHeaderIfPresent(forwarded, source, "x-mnote-source-client");
  copyHeaderIfPresent(forwarded, source, "x-mnote-actor-id");
  copyHeaderIfPresent(forwarded, source, "x-mnote-actor-type");
  copyHeaderIfPresent(forwarded, source, "user-agent");

  if (!forwarded.has("authorization") && !isDevAuthEnabled()) {
    const token = await convexAuthNextjsToken();
    if (token?.trim()) {
      forwarded.set("authorization", `Bearer ${token.trim()}`);
    }
  }

  if (!forwarded.has("x-mnote-source-channel")) {
    forwarded.set("x-mnote-source-channel", request ? "next_route" : "next_server_component");
  }
  if (!forwarded.has("x-mnote-source-client")) {
    forwarded.set("x-mnote-source-client", "wolai-frontend");
  }
  if (!forwarded.has("x-mnote-actor-id")) {
    try {
      const auth = await getAuthContext();
      if (auth.userId?.trim()) {
        forwarded.set("x-mnote-actor-id", auth.userId.trim());
        forwarded.set("x-mnote-actor-type", "user");
      }
    } catch {
      // 说明：未登录或当前上下文无法解析用户时，继续走已有 header / admin fallback。
    }
  }

  return forwarded;
}
