
interface WebhookState {
  sent: boolean;
  lastSent: number;
}

// Create hash for unique events: character-planet-extractorEndTimestamp-event
export const createWebhookHash = (
  characterId: number,
  planetId: number,
  extractorEndTimestamp: string,
  event: string
): string => {
  return `${characterId}-${planetId}-${extractorEndTimestamp}-${event}`;
};

// Get webhook state from localStorage
const getWebhookState = (hash: string): WebhookState => {
  if (typeof window === 'undefined') return { sent: false, lastSent: 0 };
  
  try {
    const stored = localStorage.getItem(`webhook_${hash}`);
    if (stored) {
      return JSON.parse(stored);
    }
  } catch (error) {
    console.warn('Failed to parse webhook state from localStorage:', error);
  }
  
  return { sent: false, lastSent: 0 };
};

// Set webhook state in localStorage
const setWebhookState = (hash: string, state: WebhookState): void => {
  if (typeof window === 'undefined') return;
  
  try {
    localStorage.setItem(`webhook_${hash}`, JSON.stringify(state));
  } catch (error) {
    console.warn('Failed to save webhook state to localStorage:', error);
  }
};

export const shouldSendWebhook = (
  characterId: number,
  planetId: number,
  extractorEndTimestamp: string,
  event: string
): boolean => {
  const hash = createWebhookHash(characterId, planetId, extractorEndTimestamp, event);
  const state = getWebhookState(hash);
  
  return !state.sent;
};

// Storage webhook tracking with 1-hour cooldown
export const shouldSendStorageWebhook = (
  characterId: number,
  planetId: number,
  storageTypeId: number,
  webhookType: string
): boolean => {
  const hash = `storage-${characterId}-${planetId}-${storageTypeId}-${webhookType}`;
  const state = getWebhookState(hash);
  
  if (!state.sent) {
    return true;
  }
  
  // Check if 1 hour has passed since last notification
  const oneHourAgo = Date.now() - (60 * 60 * 1000);
  return state.lastSent < oneHourAgo;
};

export const markStorageWebhookSent = (
  characterId: number,
  planetId: number,
  storageTypeId: number,
  webhookType: string
): void => {
  const hash = `storage-${characterId}-${planetId}-${storageTypeId}-${webhookType}`;
  setWebhookState(hash, { sent: true, lastSent: Date.now() });
};

export const markWebhookSent = (
  characterId: number,
  planetId: number,
  extractorEndTimestamp: string,
  event: string
): void => {
  const hash = createWebhookHash(characterId, planetId, extractorEndTimestamp, event);
  setWebhookState(hash, { sent: true, lastSent: Date.now() });
};

// Cleanup old webhook states (older than 7 days)
export const cleanupOldWebhookStates = (): void => {
  if (typeof window === 'undefined') return;
  
  const cutoff = Date.now() - (7 * 24 * 60 * 60 * 1000); // 7 days ago
  
  try {
    const keysToRemove: string[] = [];
    
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key && key.startsWith('webhook_')) {
        const state = JSON.parse(localStorage.getItem(key) || '{}');
        if (state.lastSent && state.lastSent < cutoff) {
          keysToRemove.push(key);
        }
      }
    }
    
    keysToRemove.forEach(key => localStorage.removeItem(key));
    
    if (keysToRemove.length > 0) {
      console.log(`🧹 Cleaned up ${keysToRemove.length} old webhook states`);
    }
  } catch (error) {
    console.warn('Failed to cleanup old webhook states:', error);
  }
};