import crypto from 'node:crypto';
import jwt from 'jsonwebtoken';

const ACCESS_TTL_SEC = Number(process.env.ACCESS_TOKEN_TTL_SEC || 900);

export function hashToken(value) {
  return crypto.createHash('sha256').update(value, 'utf8').digest('hex');
}

export function generateRefreshToken() {
  return crypto.randomBytes(48).toString('base64url');
}

export function generateCsrfToken() {
  return crypto.randomBytes(32).toString('base64url');
}

export function signAccessToken(user, sessionId) {
  return jwt.sign(
    {
      sub: user.id,
      email: user.email,
      role: user.role,
      sid: sessionId,
    },
    process.env.JWT_SECRET,
    {
      issuer: process.env.JWT_ISSUER || 'uno-click-bff',
      audience: process.env.JWT_AUDIENCE || 'uno-click-web',
      expiresIn: ACCESS_TTL_SEC,
    }
  );
}

export function verifyAccessToken(token) {
  return jwt.verify(token, process.env.JWT_SECRET, {
    issuer: process.env.JWT_ISSUER || 'uno-click-bff',
    audience: process.env.JWT_AUDIENCE || 'uno-click-web',
  });
}

export function verifyRefreshToken(token) {
  return jwt.verify(token, process.env.JWT_SECRET, {
    issuer: process.env.JWT_ISSUER || 'uno-click-bff',
    audience: process.env.JWT_AUDIENCE || 'uno-click-web',
  });
}

export function signRefreshToken(payload) {
  return jwt.sign(payload, process.env.JWT_SECRET, {
    issuer: process.env.JWT_ISSUER || 'uno-click-bff',
    audience: process.env.JWT_AUDIENCE || 'uno-click-web',
    expiresIn: '30d',
  });
}
