import { Socket } from "socket.io-client";
import { WorkerQueue } from "./queues";
import { createWorkerJob, workerLog } from "./jobFactory";
import { executeFullSync } from "./dalpuri-sync";

/**
 * Enqueue a full sync from Dalpuri (ConnectWise) to the API.
 * This will run asynchronously in the worker process.
 *
 * @param managerSocket - The manager socket connection for communicating with worker
 * @returns Promise that resolves when sync completes
 *
 * @example
 * const socket = await ensureManagerSocketReady();
 * await enqueueDalpuriFullSync(socket);
 * console.log("Sync completed!");
 */
export async function enqueueDalpuriFullSync(
  managerSocket: Socket
): Promise<void> {
  return createWorkerJob(
    managerSocket,
    WorkerQueue.DALPURI_FULL_SYNC,
    async (workerSocket) => {
      workerLog(
        workerSocket,
        "[dalpuri] Starting full sync from ConnectWise (CW) to API database",
        "INFO"
      );

      try {
        await executeFullSync(workerSocket);
        workerLog(
          workerSocket,
          "[dalpuri] Full sync completed successfully",
          "INFO"
        );
      } catch (error) {
        const errorMessage =
          error instanceof Error ? error.message : String(error);
        workerLog(
          workerSocket,
          `[dalpuri] Full sync failed: ${errorMessage}`,
          "ERROR"
        );
        throw error;
      }
    }
  );
}
