import ExtensionPolyfill from "../../extension-polyfill";
import { processStorageMessage, type StorageWorkerRequest } from "./storage-processor";

type WorkerRequest = {
  id: number;
  type: "request";
  action: string;
  payload: string;
};

type WorkerResponse<T = any> = {
  id: number;
  type: "response";
  result: T;
};

class LisioWorker{
  private _pendingRequests = new Map<
    number,
    { resolve: (value: any) => void; reject: (reason?: any) => void }
  >();

  private _requestIdCounter = 0;

  constructor(){
    if(__BUILD_TARGET__ === "extension"){
      ExtensionPolyfill.current.runtime.onMessage.addListener((message)=>{
        if(message == undefined) return;
        const { id, type, result, error } = message;
        if (type === "response" && this._pendingRequests.has(id)) {
          if (error != undefined) {
            this._pendingRequests.get(id)?.reject(new Error(error));
          } else {
            this._pendingRequests.get(id)?.resolve(result);
          }
          this._pendingRequests.delete(id);
        }
      });
    }
  }

  public callWorker<T = unknown>(action: string, payload = {}): Promise<T> {
    const id = ++this._requestIdCounter;
    const message: WorkerRequest = { id, type: "request", action, payload: JSON.stringify(payload) };
    if(__BUILD_TARGET__ === "extension"){
      return new Promise<T>((resolve, reject) => {
        this._pendingRequests.set(id, { resolve, reject });
        ExtensionPolyfill.current.sendMessage(message);
      });
    }
    // In site build, storage is processed in-process on the main thread:
    // a dedicated Worker has no access to localStorage/document.cookie.
    // Unknown actions fall through to the processor's "Unknown action" result.
    return processStorageMessage(message as StorageWorkerRequest).then(
      (response) => (response as WorkerResponse<T>).result,
    );
  }
}

/**
 * Never called. Keeps the `new Worker(new URL(...))` pattern in the source so Vite still
 * emits storage-worker.ts as a standalone, self-contained chunk in the extension build:
 * lisio-liberty's copy-storage-worker.js vendors that chunk as the background storage worker.
 */
function emitStorageWorkerChunk(): Worker {
  return new Worker(new URL("./storage-worker.ts", import.meta.url), { type: "module" });
}

export default LisioWorker;
export { emitStorageWorkerChunk };
