import { getClientId } from './clientIdentity';
import { isPreviewRuntime } from './previewRuntime';

export const NOTIFICATION_DEVICE_ID_STORAGE_KEY = 'work-server.notification.device-id';
const PREVIEW_NOTIFICATION_DEVICE_ID_STORAGE_KEY = 'work-server.preview-runtime.notification.device-id';

export type AutomationNotificationPreferenceTarget = {
  targetKind: 'client';
  targetId: string;
};

function getNotificationIdentityStorage() {
  if (typeof window === 'undefined') {
    return null;
  }

  const isPreview = isPreviewRuntime();

  return {
    storage: isPreview ? window.sessionStorage : window.localStorage,
    key: isPreview ? PREVIEW_NOTIFICATION_DEVICE_ID_STORAGE_KEY : NOTIFICATION_DEVICE_ID_STORAGE_KEY,
  };
}

function generateNotificationDeviceId() {
  if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
    return `web-${crypto.randomUUID()}`;
  }

  return `web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}

function shouldRotateLegacyNotificationDeviceId(savedDeviceId: string) {
  const normalizedDeviceId = savedDeviceId.trim();

  if (!normalizedDeviceId) {
    return false;
  }

  const currentClientId = getClientId().trim();

  return Boolean(currentClientId) && normalizedDeviceId === currentClientId;
}

export function getSavedNotificationDeviceId() {
  const storageConfig = getNotificationIdentityStorage();

  if (!storageConfig) {
    return '';
  }

  const saved = storageConfig.storage.getItem(storageConfig.key)?.trim() ?? '';

  if (saved) {
    if (shouldRotateLegacyNotificationDeviceId(saved)) {
      const rotated = generateNotificationDeviceId();
      storageConfig.storage.setItem(storageConfig.key, rotated);
      return rotated;
    }

    return saved;
  }

  const generated = generateNotificationDeviceId();
  storageConfig.storage.setItem(storageConfig.key, generated);
  return generated;
}

export function clearNotificationIdentity() {
  const storageConfig = getNotificationIdentityStorage();

  if (!storageConfig) {
    return;
  }

  storageConfig.storage.removeItem(storageConfig.key);
}

export function getAutomationNotificationPreferenceTarget(): AutomationNotificationPreferenceTarget | null {
  const deviceId = getSavedNotificationDeviceId();

  if (!deviceId) {
    return null;
  }

  return {
    targetKind: 'client',
    targetId: deviceId,
  };
}
