var crypto = require('crypto');

function hashToken(token) {
  return crypto.createHash('sha256').update(token).digest('hex');
}

function parseUserAgent(ua) {
  if (!ua) return 'Unknown device';

  // Native PedScribe app (Capacitor appends "PedScribe-Android" / "PedScribe-iOS")
  if (/PedScribe-Android/i.test(ua)) return 'PedScribe (Android)';
  if (/PedScribe-iOS/i.test(ua))     return 'PedScribe (iOS)';
  if (/Capacitor/i.test(ua)) {
    if (/Android/i.test(ua)) return 'PedScribe (Android)';
    if (/iPhone|iPad|iOS/i.test(ua)) return 'PedScribe (iOS)';
    return 'PedScribe app';
  }

  var browser = 'Unknown browser';
  var os = 'Unknown OS';

  if (/Edg\//.test(ua))           browser = 'Edge';
  else if (/OPR\/|Opera/.test(ua)) browser = 'Opera';
  else if (/Firefox\//.test(ua))  browser = 'Firefox';
  else if (/Safari\//.test(ua) && !/Chrome/.test(ua)) browser = 'Safari';
  else if (/Chrome\//.test(ua))   browser = 'Chrome';

  if (/Windows/.test(ua))         os = 'Windows';
  else if (/Mac OS X/.test(ua))   os = 'macOS';
  else if (/Android/.test(ua))    os = 'Android';
  else if (/iPhone|iPad/.test(ua)) os = 'iOS';
  else if (/Linux/.test(ua))      os = 'Linux';
  else if (/CrOS/.test(ua))       os = 'ChromeOS';

  return browser + ' on ' + os;
}

function generateSessionId() {
  return crypto.randomUUID();
}

module.exports = { hashToken, parseUserAgent, generateSessionId };
