import { fromCallback } from "xstate";

import { Logger } from "@/utils/logger";

import {
  readLocalHistorySnapshot,
  resolveHistoryCacheIdentity,
  syncNetworkHistory,
} from "../../chat-history-sync";
import type { ChatEvent } from "../../chat-events";

const log = new Logger("StoresChatChatHistoryFlow");

export const loadHistoryActor = fromCallback<ChatEvent>(({ sendBack }) => {
  let cancelled = false;

  void (async () => {
    const cacheIdentity = await resolveHistoryCacheIdentity();
    const localSnapshot = await readLocalHistorySnapshot(cacheIdentity);
    if (cancelled) return;
    sendBack({
      type: "ChatLocalHistoryLoaded",
      output: localSnapshot,
    });

    const networkSnapshot = await syncNetworkHistory(
      localSnapshot.localCount,
      cacheIdentity,
    );
    if (cancelled || !networkSnapshot) return;
    sendBack({
      type: "ChatNetworkHistoryLoaded",
      output: networkSnapshot,
    });
  })().catch((error: unknown) => {
    if (cancelled) return;
    log.error("[chat-machine] loadHistoryActor failed", { error });
    sendBack({ type: "ChatHistoryLoadFailed", error });
  });

  return () => {
    cancelled = true;
  };
});
