const crypto = require('crypto');

const WINDOW_MS = 30 * 60 * 1000;

function getSecret() {
  const secret = String(
    process.env.AISFOR_CHAIN_WALLET_SSO_SECRET ||
    process.env.AISFOR_CHAIN_ADMIN_SESSION_SECRET ||
    process.env.PLAIS_EVM_VAULT_SECRET ||
    ''
  );
  if (secret.length < 24) throw new Error('Wallet CSRF secret is not configured.');
  return secret;
}

function signature(userId, action, bucket) {
  return crypto
    .createHmac('sha256', getSecret())
    .update(`${String(userId)}:${String(action)}:${bucket}`)
    .digest('base64url');
}

function createToken(userId, action) {
  const bucket = Math.floor(Date.now() / WINDOW_MS);
  return `${bucket}.${signature(userId, action, bucket)}`;
}

function verifyToken(token, userId, action) {
  const [bucketText, provided] = String(token || '').split('.');
  const bucket = Number(bucketText);
  if (!Number.isInteger(bucket) || !provided) return false;
  const current = Math.floor(Date.now() / WINDOW_MS);
  if (bucket < current - 1 || bucket > current) return false;
  const expected = signature(userId, action, bucket);
  const left = Buffer.from(provided);
  const right = Buffer.from(expected);
  return left.length === right.length && crypto.timingSafeEqual(left, right);
}

module.exports = { createToken, verifyToken };
