import { isStorageWorkerRequest, processStorageMessage } from "./storage-processor";

function init(){
  if(__BUILD_TARGET__ === "extension"){
    import("../../extension-polyfill").then((m)=>{
      const ExtensionPolyfill = m.default;
      
      // Must stay synchronous: returning a promise (as an async listener does) claims the reply
      // for every runtime message, so other background listeners could never answer theirs.
      ExtensionPolyfill.current.runtime.onMessage.addListener((message: unknown)=>{
        if(!isStorageWorkerRequest(message)){
          return; // not ours: let other listeners answer
        }
        void processStorageMessage(message).then((response)=>{
          if(response != undefined){
            ExtensionPolyfill.current.sendMessage(response);
          }
        }).catch((error)=>{
          console.error(`[StorageWorker] Failed to process "${message.action}"`, error);
          // Always answer: without a reply the caller's callWorker promise never settles,
          // which froze every toggle awaiting a storage write (e.g. reset left nav tabs active).
          ExtensionPolyfill.current.sendMessage({
            id: message.id,
            type: "response",
            error: String(error),
          });
        });
        // Returns undefined on purpose: the reply is broadcast and matched by id, not sent via sendResponse.
      });
    });
  
  }else{
    onmessage = async (event)=>{
      const response = await processStorageMessage(event.data);
      postMessage(response);
    }
  }
}

init();