import UAParser from 'ua-parser-js';
import type { DeviceInfo, BrowserInfo, OSInfo } from '../types.js';

export const parseUserAgent = (ua: string): {
  device: DeviceInfo;
  browser: BrowserInfo;
  os: OSInfo;
} => {
  const parser = new UAParser(ua);
  const result = parser.getResult();

  const deviceType = result.device.type as DeviceInfo['type'] | undefined;
  const type: DeviceInfo['type'] =
    deviceType && ['mobile', 'tablet', 'wearable', 'smarttv', 'desktop'].includes(deviceType)
      ? deviceType
      : 'desktop';

  return {
    device: {
      type,
      vendor: result.device.vendor || undefined,
      model: result.device.model || undefined,
    },
    browser: {
      name: result.browser.name ?? 'Unknown',
      version: result.browser.version ?? '',
      full: [result.browser.name, result.browser.version].filter(Boolean).join(' '),
    },
    os: {
      name: result.os.name ?? 'Unknown',
      version: result.os.version ?? '',
      full: [result.os.name, result.os.version].filter(Boolean).join(' '),
    },
  };
};
