import crypto from "crypto";
import { logger } from "./logger";

const secret = process.env.AGX_HMAC_SECRET || "";
const required = (process.env.AGX_HMAC_REQUIRED || "true") === "true";
const windowSeconds = Number(process.env.AGX_HMAC_WINDOW_SECONDS || 300);

export function buildSignature(ts: string, nonce: string, body: string) {
  return crypto.createHmac("sha256", secret).update(`${ts}.${nonce}.${body}`).digest("hex");
}

export function verifySignature(headers: any, rawBody: string) {
  if (!required) return { ok: true, reason: "not_required" };
  if (!secret) return { ok: false, reason: "missing_secret" };

  const sig = headers["x-agx-signature"] as string | undefined;
  const ts = headers["x-agx-timestamp"] as string | undefined;
  const nonce = headers["x-agx-nonce"] as string | undefined;

  if (!sig || !ts || !nonce) return { ok: false, reason: "missing_headers" };

  const tsNum = Number(ts);
  const now = Date.now();
  if (Number.isNaN(tsNum) || Math.abs(now - tsNum) > windowSeconds * 1000) {
    return { ok: false, reason: "timestamp_out_of_window" };
  }

  const expected = buildSignature(ts, nonce, rawBody);
  const ok = crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
  return { ok, reason: ok ? "ok" : "invalid_signature" };
}
