import { removeDocuments } from "../anythingllm/anythingllm.client.js";
import type { CleanupJob } from "./queue.js";
import { logError } from "../utils/logger.js";
import { readIndex, writeIndex } from "../notes/notes.storage.js";

export async function handleCleanupJob(job: CleanupJob): Promise<void> {
  try {
    await removeDocuments([job.oldLocation]);
    const index = await readIndex();
    const updated = index.map((item) => {
      if (item.id === job.id) {
        return {
          ...item,
          sync: {
            ...item.sync,
            cleanupPending: false
          }
        };
      }
      return item;
    });
    await writeIndex(updated);
  } catch (error) {
    logError("Temizlik kuyrugu hatasi", { error: (error as Error).message });
    throw error;
  }
}
