import { TodoistApi as h } from "@doist/todoist-sdk";
import { P as T } from "./mcp-server-zOuk6rId.js";
const p = /* @__PURE__ */ new Set([401, 403]);
function w(e) {
  const t = T(e);
  if (t !== void 0)
    return t;
  if (e !== null && typeof e == "object" && "response" in e)
    return T(e.response);
}
async function y(e, t) {
  const r = new h(e, { baseUrl: t });
  try {
    return await r.getUser(), !0;
  } catch (i) {
    const o = w(i);
    if (o !== void 0 && p.has(o))
      return !1;
    throw i;
  }
}
const _ = 3e5, v = 12e4, A = 1e4, n = /* @__PURE__ */ new Map();
function C(e, t) {
  return t ? `${e}::${t}` : e;
}
function E() {
  const e = Date.now();
  for (const [t, r] of n)
    e >= r.expiresAt && n.delete(t);
}
function S(e) {
  const t = n.get(e);
  if (t && Date.now() < t.expiresAt)
    return t.valid;
  t && n.delete(e);
}
function k(e, t, r) {
  n.size >= A && E(), n.size >= A && n.clear(), n.set(e, { valid: t, expiresAt: Date.now() + r });
}
function D(e) {
  return e ? `Bearer resource_metadata="${e}"` : "Bearer";
}
function d(e, t) {
  e.status(401).set("WWW-Authenticate", D(t)).json({
    error: "invalid_token",
    error_description: "Todoist API token is invalid or expired"
  });
}
function x(e) {
  const t = e.type === "static" ? _ : v, r = e.cacheTtlMs ?? t, { resourceMetadataUrl: i } = e;
  return async (o, c, s) => {
    const u = e.type === "static" ? e.apiKey : e.getApiKey(o);
    if (!u) {
      d(c, i);
      return;
    }
    const f = C(u, e.baseUrl), l = S(f);
    if (l !== void 0) {
      l ? s() : d(c, i);
      return;
    }
    try {
      const a = await y(u, e.baseUrl);
      k(f, a, r), a ? s() : d(c, i);
    } catch (a) {
      console.warn("[Token validation] Transient error, proceeding:", a), s();
    }
  };
}
export {
  x as r,
  y as v
};
