import FingerprintJS from '@fingerprintjs/fingerprintjs';
import { browserApi } from '@/browser';

export const getBrowserAgent = () => {
  return navigator.userAgent;
};

export const getBrowserName = () => {
  const userAgent = navigator.userAgent.toLowerCase();

  if (userAgent.includes('chrome') && userAgent.includes('edg')) return 'Edge';
  if (userAgent.includes('chrome') && userAgent.includes('opr')) return 'Opera';
  if (userAgent.includes('chrome')) return 'Chrome';
  if (userAgent.includes('firefox')) return 'Firefox';
  if (userAgent.includes('safari')) return 'Safari';

  return 'Unknown';
};

export const getPlatformInfo = async () => {
  return await browserApi.runtime.getPlatformInfo();
};

export const getIpAddress = async () => {
  const response = await fetch('https://service.autoshopee.com/ip?type=json');
  return (await response.json()).ip;
};

export const getHashProfileId = async (input) => {
  const encoder = new TextEncoder();
  const data = encoder.encode(input);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');

  return hashHex
    .match(/.{1,2}/g)
    .slice(0, 6)
    .join('-')
    .toUpperCase();
};

export const getFingerprintId = async () => {
  const fpLoad = await FingerprintJS.load();
  const fsGet = await fpLoad.get();
  return fsGet.visitorId;
};
