import FingerprintJS from '@fingerprintjs/fingerprintjs';

let fpPromise = null;

/**
 * @returns {Promise} Promise с экземпляром FingerprintJS
 */
const initFingerprint = () => {
  if (!fpPromise) {
    fpPromise = FingerprintJS.load();
  }
  return fpPromise;
};

/**
 * @returns {Promise<string>} Fingerprint ID
 */
export const getFingerprint = async () => {
  try {
    const savedFingerprint = localStorage.getItem('fingerprint');
    if (savedFingerprint) {
      return savedFingerprint;
    }

    const fp = await initFingerprint();
    const result = await fp.get();
    const fingerprint = result.visitorId;

    localStorage.setItem('fingerprint', fingerprint);
    return fingerprint;
  } catch (error) {
    console.error('Error getting fingerprint:', error);
    const fallbackFingerprint = `fallback_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    localStorage.setItem('fingerprint', fallbackFingerprint);
    return fallbackFingerprint;
  }
};

export const clearFingerprint = () => {
  localStorage.removeItem('fingerprint');
};

