import { DateTime } from 'luxon';

export interface WebhookState {
  lastSent: string;
  type: string;
  planetId: number;
  characterId: number;
  extractorPinId?: number;
  storageTypeId?: number;
}

// In-memory storage for webhook states (in production, you might want to use localStorage or a database)
const webhookStates = new Map<string, WebhookState>();

export const generateWebhookKey = (
  characterId: number,
  planetId: number,
  type: string,
  extractorPinId?: number,
  storageTypeId?: number
): string => {
  const parts = [characterId, planetId, type];
  if (extractorPinId !== undefined) parts.push(`extractor-${extractorPinId}`);
  if (storageTypeId !== undefined) parts.push(`storage-${storageTypeId}`);
  return parts.join('-');
};

export const shouldSendWebhook = (
  characterId: number,
  planetId: number,
  type: string,
  extractorPinId?: number,
  storageTypeId?: number
): boolean => {
  const key = generateWebhookKey(characterId, planetId, type, extractorPinId, storageTypeId);
  const state = webhookStates.get(key);
  
  if (!state) {
    return true; // First time, send webhook
  }
  
  const lastSent = DateTime.fromISO(state.lastSent);
  const now = DateTime.now();
  
  // For expired extractors, resend every hour
  if (type === 'extractor_expired') {
    return now.diff(lastSent, 'hours').hours >= 1;
  }
  
  // For other alerts, resend every 4 hours
  return now.diff(lastSent, 'hours').hours >= 4;
};

export const markWebhookSent = (
  characterId: number,
  planetId: number,
  type: string,
  extractorPinId?: number,
  storageTypeId?: number
): void => {
  const key = generateWebhookKey(characterId, planetId, type, extractorPinId, storageTypeId);
  webhookStates.set(key, {
    lastSent: DateTime.now().toISO(),
    type,
    planetId,
    characterId,
    extractorPinId,
    storageTypeId
  });
};

export const resetWebhookState = (
  characterId: number,
  planetId: number,
  type: string,
  extractorPinId?: number,
  storageTypeId?: number
): void => {
  const key = generateWebhookKey(characterId, planetId, type, extractorPinId, storageTypeId);
  webhookStates.delete(key);
};

// Reset extractor webhook states when extractors are refreshed (duration is "full" again)
export const resetExtractorWebhookStates = (
  characterId: number,
  planetId: number,
  extractorPinId: number
): void => {
  resetWebhookState(characterId, planetId, 'extractor_expiring', extractorPinId);
  resetWebhookState(characterId, planetId, 'extractor_expired', extractorPinId);
};

// Clear old webhook states (older than 7 days)
export const cleanupOldWebhookStates = (): void => {
  const cutoff = DateTime.now().minus({ days: 7 });
  
  for (const [key, state] of webhookStates.entries()) {
    const lastSent = DateTime.fromISO(state.lastSent);
    if (lastSent < cutoff) {
      webhookStates.delete(key);
    }
  }
};
