import crypto from 'crypto';

const pairingTokens = /* @__PURE__ */ new Map();
setInterval(() => {
  const now = /* @__PURE__ */ new Date();
  for (const [token, data] of pairingTokens.entries()) {
    if (data.expiresAt < now || data.used) {
      pairingTokens.delete(token);
    }
  }
}, 6e4);
async function handler(req, res) {
  try {
    const token = crypto.randomBytes(32).toString("hex");
    const expiresAt = new Date(Date.now() + 5 * 60 * 1e3);
    pairingTokens.set(token, {
      expiresAt,
      used: false
    });
    const serverUrl = process.env.EXTERNAL_URL || process.env.SERVER_URL || `${req.protocol}://${req.get("host")}`;
    const qrData = JSON.stringify({
      type: "cloudvault_pairing",
      version: "1.0",
      serverUrl,
      token,
      expiresAt: expiresAt.toISOString()
    });
    res.status(200).json({
      success: true,
      token,
      expiresAt: expiresAt.toISOString(),
      qrData,
      message: "Pairing token generated successfully"
    });
  } catch (error) {
    console.error("Token generation error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to generate pairing token",
      message: String(error)
    });
  }
}
function validatePairingToken(token) {
  console.log("🔍 Validating token:", token.substring(0, 10) + "...");
  console.log("📊 Total tokens in memory:", pairingTokens.size);
  const tokenData = pairingTokens.get(token);
  if (!tokenData) {
    console.log("❌ Token not found in memory");
    return false;
  }
  if (tokenData.used) {
    console.log("❌ Token already used");
    return false;
  }
  if (tokenData.expiresAt < /* @__PURE__ */ new Date()) {
    console.log("❌ Token expired");
    pairingTokens.delete(token);
    return false;
  }
  tokenData.used = true;
  console.log("✅ Token validated successfully");
  return true;
}
function checkPairingToken(token) {
  const tokenData = pairingTokens.get(token);
  if (!tokenData) {
    return { exists: false };
  }
  return {
    exists: true,
    used: tokenData.used,
    expired: tokenData.expiresAt < /* @__PURE__ */ new Date()
  };
}

export { checkPairingToken, handler as default, validatePairingToken };
