import "server-only";

import { licitationsConfig } from "@/lib/licitations/config";

function readBearerToken(value: string | null) {
  if (!value) {
    return "";
  }

  const normalized = value.trim();
  if (!normalized.toLowerCase().startsWith("bearer ")) {
    return "";
  }

  return normalized.slice(7).trim();
}

export function isAuthorizedCronRequest(request: Request) {
  const syncToken = request.headers.get("x-sync-token")?.trim() ?? "";
  if (licitationsConfig.syncCronToken && syncToken && syncToken === licitationsConfig.syncCronToken) {
    return true;
  }

  const bearerToken = readBearerToken(request.headers.get("authorization"));
  if (licitationsConfig.cronSecret && bearerToken && bearerToken === licitationsConfig.cronSecret) {
    return true;
  }

  const url = new URL(request.url);
  const queryToken = url.searchParams.get("token")?.trim() ?? "";
  if (licitationsConfig.syncCronToken && queryToken && queryToken === licitationsConfig.syncCronToken) {
    return true;
  }

  return false;
}
