import storageAvailable from 'storage-available';

// How long to remember that we've already processed this signin/signup (1 hour)
export const ANTI_ABUSE_TRACKING_TTL_HOURS = 0.5;
export const ANTI_ABUSE_TRACKING_TTL_MS =
  ANTI_ABUSE_TRACKING_TTL_HOURS * 60 * 60 * 1000; // 1 hour in milliseconds

/**
 * Get anti-abuse tracking data from localStorage
 * @param trackingKey - The key to look up in localStorage
 * @returns Object with optional createdAt timestamp and turnstile token
 */
export const getAntiAbuseTracking = (
  trackingKey: string
): { createdAt?: number; turnstileToken?: string } => {
  let trackedObject: { createdAt?: number; turnstileToken?: string } = {};
  try {
    if (storageAvailable('localStorage')) {
      const trackedValue = localStorage.getItem(trackingKey);
      if (trackedValue) {
        trackedObject = JSON.parse(trackedValue);
      }
    }
  } catch (e) {
    // Invalid JSON, treat as no tracking data
  }
  return trackedObject;
};

/**
 * Set anti-abuse tracking data in localStorage with creation time and turnstile token
 * @param trackingKey - The key to store in localStorage
 * @param turnstileToken - The Cloudflare Turnstile token (optional)
 */
export const setAntiAbuseTracking = (
  trackingKey: string,
  turnstileToken?: string
): void => {
  if (storageAvailable('localStorage')) {
    const trackingData: { createdAt: number; turnstileToken?: string } = {
      createdAt: Date.now(),
    };
    if (turnstileToken) {
      trackingData.turnstileToken = turnstileToken;
    }
    localStorage.setItem(trackingKey, JSON.stringify(trackingData));
  }
};

/**
 * Clear anti-abuse tracking data for a specific key
 * @param trackingKey - The key to remove from localStorage
 */
export const clearAntiAbuseTracking = (trackingKey: string): void => {
  if (storageAvailable('localStorage')) {
    localStorage.removeItem(trackingKey);
  }
};

/**
 * Check if anti-abuse tracking has expired for a given key
 * @param trackingKey - The key to check
 * @returns boolean indicating if tracking has expired or doesn't exist
 */
export const hasAntiAbuseTrackingExpired = (trackingKey: string): boolean => {
  const trackedObject = getAntiAbuseTracking(trackingKey);
  // Consider expired if:
  // 1. No createdAt timestamp exists
  // 2. Current time is past TTL from creation time
  const expired =
    !trackedObject.createdAt ||
    Date.now() - trackedObject.createdAt > ANTI_ABUSE_TRACKING_TTL_MS;
  return expired;
};

/**
 * Get the stored Turnstile token for a given key
 * @param trackingKey - The key to check
 * @returns The stored Turnstile token or null if not found
 */
export const getStoredTurnstileToken = (trackingKey: string): string | null => {
  const trackedObject = getAntiAbuseTracking(trackingKey);
  return trackedObject.turnstileToken || null;
};
