// Single implementation of the "safe" chrome API wrappers shared by every
// context. All of them guard against the extension context being invalidated
// (extension reloaded/updated while a page, popup, or options view is open),
// which otherwise throws from any chrome.* call.

export function isExtensionValid(): boolean {
  try {
    return typeof chrome !== 'undefined' && !!chrome.runtime?.id;
  } catch {
    return false;
  }
}

export function safeStorageGet(
  keys: string[],
  callback: (result: Record<string, any>) => void,
  storage: chrome.storage.StorageArea = chrome.storage.local,
): void {
  try {
    if (!isExtensionValid()) return;
    storage.get(keys, callback);
  } catch (err) {
    console.warn('LexAI: Extension context invalidated', err);
  }
}

export function safeStorageSet(
  data: Record<string, unknown>,
  callback?: () => void,
  storage: chrome.storage.StorageArea = chrome.storage.local,
): void {
  try {
    if (!isExtensionValid()) return;
    if (callback) {
      storage.set(data, callback);
    } else {
      storage.set(data);
    }
  } catch (err) {
    console.warn('LexAI: Extension context invalidated', err);
  }
}

// Sends a message to the background worker. Returns null (never throws) when
// the extension context is gone or the send fails. `onContextInvalidated` lets
// UI contexts react (e.g. the content script shows a "please refresh" toast).
export async function safeSendMessage<T = any>(
  message: Record<string, unknown>,
  onContextInvalidated?: () => void,
): Promise<T | null> {
  if (!isExtensionValid()) {
    onContextInvalidated?.();
    return null;
  }
  try {
    return await chrome.runtime.sendMessage(message);
  } catch (err) {
    if (
      String(err).includes('Extension context invalidated') ||
      String(err).includes('message channel closed')
    ) {
      onContextInvalidated?.();
    } else {
      console.warn('LexAI: sendMessage failed', err);
    }
    return null;
  }
}
