import { timingSafeEqual } from "node:crypto";

import { env } from "@/lib/env";

const BEARER_PREFIX = "Bearer ";

export type IntegrationAuthResult =
  | { ok: true }
  | { ok: false; status: 401 | 503; message: string };

export function validateIntegrationBearer(authHeader: string | null): IntegrationAuthResult {
  if (!env.ELEVASPEED_INTEGRATION_API_KEY) {
    return { ok: false, status: 503, message: "Integration API not configured" };
  }
  if (!authHeader || !authHeader.startsWith(BEARER_PREFIX)) {
    return { ok: false, status: 401, message: "Missing or malformed Authorization header" };
  }
  const provided = authHeader.slice(BEARER_PREFIX.length);

  const encoder = new TextEncoder();
  const a = encoder.encode(provided);
  const b = encoder.encode(env.ELEVASPEED_INTEGRATION_API_KEY);

  if (a.length !== b.length) return { ok: false, status: 401, message: "Invalid key" };
  if (!timingSafeEqual(a, b)) return { ok: false, status: 401, message: "Invalid key" };

  return { ok: true };
}
