// Share service for creating 7-day shareable links
// Uses localStorage to store shared configs with expiration

const SHARE_PREFIX = 'ossm_share_';
const SHARE_EXPIRY_DAYS = 7;

export const createShareLink = (config) => {
  // Generate a unique ID for this share
  const shareId = `share_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
  
  // Calculate expiration date (7 days from now)
  const expiresAt = Date.now() + (SHARE_EXPIRY_DAYS * 24 * 60 * 60 * 1000);
  
  // Store the config in localStorage with expiration
  const shareData = {
    config,
    expiresAt,
    createdAt: Date.now()
  };
  
  try {
    localStorage.setItem(`${SHARE_PREFIX}${shareId}`, JSON.stringify(shareData));
    
    // Clean up expired shares
    cleanupExpiredShares();
    
    // Return the shareable URL
    const currentUrl = window.location.origin + window.location.pathname;
    return `${currentUrl}?share=${shareId}`;
  } catch (error) {
    console.error('Error creating share link:', error);
    // If localStorage is full, try using sessionStorage as fallback
    try {
      sessionStorage.setItem(`${SHARE_PREFIX}${shareId}`, JSON.stringify(shareData));
      const currentUrl = window.location.origin + window.location.pathname;
      return `${currentUrl}?share=${shareId}&session=true`;
    } catch (fallbackError) {
      console.error('Error with fallback storage:', fallbackError);
      throw new Error('Unable to create share link. Please try again.');
    }
  }
};

export const getSharedConfig = (shareId, isSession = false) => {
  const storage = isSession ? sessionStorage : localStorage;
  const key = `${SHARE_PREFIX}${shareId}`;
  const shareDataStr = storage.getItem(key);
  
  if (!shareDataStr) {
    return null;
  }
  
  try {
    const shareData = JSON.parse(shareDataStr);
    
    // Check if expired
    if (shareData.expiresAt && Date.now() > shareData.expiresAt) {
      storage.removeItem(key);
      return null;
    }
    
    return shareData.config;
  } catch (error) {
    console.error('Error reading share data:', error);
    return null;
  }
};

export const cleanupExpiredShares = () => {
  try {
    const keys = Object.keys(localStorage);
    const now = Date.now();
    
    keys.forEach(key => {
      if (key.startsWith(SHARE_PREFIX)) {
        try {
          const shareData = JSON.parse(localStorage.getItem(key));
          if (shareData.expiresAt && now > shareData.expiresAt) {
            localStorage.removeItem(key);
          }
        } catch (e) {
          // Invalid data, remove it
          localStorage.removeItem(key);
        }
      }
    });
  } catch (error) {
    console.error('Error cleaning up expired shares:', error);
  }
};

export const deleteShare = (shareId, isSession = false) => {
  const storage = isSession ? sessionStorage : localStorage;
  storage.removeItem(`${SHARE_PREFIX}${shareId}`);
};
