import { NextRequest } from "next/server";

// Identity resolution for both this app's own /api/* routes AND the
// Authorization header forwarded on to the aicommand backend (which itself
// forwards it on to hub's /api/v1/ai/key + /ai/usage for per-user billing
// attribution — see KeyController.php on the hub side). So the resolved
// token here isn't just a presence check anymore: whichever token comes out
// of resolveCaller() is literally what hub bills against.
//
// The portal now passes a real per-user hub JWT through the embed script on
// every request, so this app requires one by default: a missing user_id or
// Authorization is rejected rather than silently billed against a shared
// fallback account. Set USE_DEFAULT_AUTH=true (plus DEFAULT_USER_ID /
// DEFAULT_USER_TOKEN) only if you need to support a caller without a real
// per-user token again — e.g. local dev, or a future anonymous embed.
const USE_DEFAULT_AUTH = process.env.USE_DEFAULT_AUTH === "true";
const DEFAULT_USER_ID = process.env.DEFAULT_USER_ID || "dummy-user-001";
const DEFAULT_USER_TOKEN =
  process.env.DEFAULT_USER_TOKEN || process.env.BACKEND_API_TOKEN;

export interface ResolvedCaller {
  userId: string | null;
  token: string | null;
}

export function resolveCaller(
  req: NextRequest,
  candidateUserId?: string | null,
): ResolvedCaller {
  const authHeader = req.headers.get("authorization");
  const bearerMatch = authHeader?.match(/^Bearer\s+(.+)$/i);

  let userId = candidateUserId || null;
  let token = bearerMatch ? bearerMatch[1] : null;

  if ((!userId || !token) && USE_DEFAULT_AUTH) {
    userId = userId || DEFAULT_USER_ID;
    token = token || DEFAULT_USER_TOKEN || null;
  }

  return { userId, token };
}
