const { getApiToken, isAuthRequired } = require("./settings-store");

const PRINT_REPLAY_SECRET = (process.env.PRINT_REPLAY_SECRET || "").trim();
const PRINT_METRICS_TOKEN = (process.env.PRINT_METRICS_TOKEN || "").trim();

function getEffectivePrintToken() {
  if (process.env.PRINT_API_TOKEN) return process.env.PRINT_API_TOKEN.trim();
  return getApiToken();
}

function bearerMatches(req, expected) {
  if (!expected) return true;
  const auth = String(req.headers.authorization || "").trim();
  return auth === `Bearer ${expected}`;
}

function requirePrintApiToken(req, res, next) {
  if (!isAuthRequired()) return next();
  const token = getEffectivePrintToken();
  if (!token) return next();
  if (bearerMatches(req, token)) return next();
  return res.status(401).json({ error: "UNAUTHORIZED" });
}

function authorizeMetrics(req) {
  if (!PRINT_METRICS_TOKEN) return true;
  return bearerMatches(req, PRINT_METRICS_TOKEN);
}

function authorizeReplay(req) {
  if (!PRINT_REPLAY_SECRET) return true;
  const tok = req.headers["x-print-replay-token"];
  const raw = Array.isArray(tok) ? tok[0] : tok;
  if (String(raw || "").trim() === PRINT_REPLAY_SECRET) return true;
  return bearerMatches(req, PRINT_REPLAY_SECRET);
}

function verifyRequestSignature(req) {
  const secret = getEffectivePrintToken();
  if (!secret || !req.headers["x-siraya-signature"]) return true;
  const crypto = require("crypto");
  const body = JSON.stringify(req.body || {});
  const expected = crypto
    .createHmac("sha256", secret)
    .update(body)
    .digest("hex");
  return expected === String(req.headers["x-siraya-signature"]);
}

function requireSignatureIfPresent(req, res, next) {
  if (!req.headers["x-siraya-signature"]) return next();
  if (verifyRequestSignature(req)) return next();
  return res.status(401).json({ error: "INVALID_SIGNATURE" });
}

module.exports = {
  requirePrintApiToken,
  authorizeMetrics,
  authorizeReplay,
  requireSignatureIfPresent,
  getEffectivePrintToken,
};
