type CookieValue = string | undefined;

type RequestHeadersLike = Record<string, unknown> | undefined;

type RequestWithCookies = {
  cookies?: Record<string, CookieValue>;
  headers?: RequestHeadersLike;
};

const pickFirstStringHeader = (value: unknown): string | undefined => {
  if (typeof value === "string") {
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : undefined;
  }

  if (Array.isArray(value)) {
    for (const entry of value) {
      const normalized = pickFirstStringHeader(entry);
      if (normalized) return normalized;
    }
  }

  return undefined;
};

export const resolveAuthorizationHeader = (headers: RequestHeadersLike): string | undefined => {
  const raw = headers?.["authorization"];
  return pickFirstStringHeader(raw);
};

export const extractBearerToken = (headers: RequestHeadersLike): string | undefined => {
  const authHeader = resolveAuthorizationHeader(headers);
  if (authHeader && authHeader.startsWith("Bearer ")) {
    const token = authHeader.slice("Bearer ".length).trim();
    return token.length > 0 ? token : undefined;
  }
  return undefined;
};

export const extractAccessTokenFromRequest = (request: RequestWithCookies): string | undefined => {
  const headerToken = extractBearerToken(request.headers);
  if (headerToken) return headerToken;

  const cookieToken = request.cookies?.["access_token"];
  return typeof cookieToken === "string" && cookieToken.length > 0 ? cookieToken : undefined;
};
