export type ExtensionSyncResult = {
  success?: boolean;
  valid?: boolean;
  synced?: boolean;
  message?: string;
  username?: string;
  account_id?: string;
};

export function isExtensionBridgePresent() {
  return document.documentElement.dataset.haixunExtension === "1";
}

export function normalizeExtensionSyncResult(raw: ExtensionSyncResult): ExtensionSyncResult {
  const nested =
    raw && typeof (raw as { data?: ExtensionSyncResult }).data === "object"
      ? ((raw as { data?: ExtensionSyncResult }).data as ExtensionSyncResult)
      : null;

  const payload = nested ?? raw;
  return {
    success: payload.success !== false,
    valid: payload.valid !== false,
    synced: payload.synced ?? true,
    message: payload.message,
    username: payload.username,
    account_id: payload.account_id,
  };
}

export function pingExtensionBridge() {
  window.postMessage({ type: "HAIXUN_PING_EXTENSION" }, "*");
}

export function waitForExtensionBridge(timeoutMs = 8000): Promise<boolean> {
  if (isExtensionBridgePresent()) return Promise.resolve(true);

  return new Promise((resolve) => {
    const started = Date.now();

    const onMessage = (event: MessageEvent) => {
      if (event.source !== window) return;
      if (event.data?.type !== "HAIXUN_EXTENSION_READY") return;
      cleanup();
      resolve(true);
    };

    const timer = window.setInterval(() => {
      pingExtensionBridge();
      if (isExtensionBridgePresent()) {
        cleanup();
        resolve(true);
        return;
      }
      if (Date.now() - started >= timeoutMs) {
        cleanup();
        resolve(false);
      }
    }, 500);

    function cleanup() {
      window.removeEventListener("message", onMessage);
      window.clearInterval(timer);
    }

    window.addEventListener("message", onMessage);
    pingExtensionBridge();
  });
}

export function requestExtensionSync(input: {
  accountId: string;
  serverUrl: string;
}): Promise<ExtensionSyncResult> {
  void input;
  return Promise.reject(new Error("Chrome session 同步暫時停用：舊版 extension 需要透過頁面訊息傳送 JWT，已因安全風險關閉。"));
}
