/**
 * In-memory progress store for long-running sync/export jobs.
 */

export type SyncProgress = {
  jobId: string;
  downloaded: number;
  total?: number;
  status: "running" | "done" | "error";
  phase?: string;
  message?: string;
  note?: string;
  phaseCurrent?: number;
  phaseTotal?: number;
};

type ProgressStore = Map<string, SyncProgress>;

const g = globalThis as {
  __parcelSyncProgressStore?: ProgressStore;
  __progressCleanupTimer?: ReturnType<typeof setInterval>;
};
const store: ProgressStore = g.__parcelSyncProgressStore ?? new Map();
g.__parcelSyncProgressStore = store;

// Periodic cleanup of stale progress entries (every 30 minutes)
if (!g.__progressCleanupTimer) {
  g.__progressCleanupTimer = setInterval(() => {
    for (const [jobId, p] of store.entries()) {
      if (p.status === "done" || p.status === "error") {
        store.delete(jobId);
      }
    }
  }, 30 * 60_000);
}

export const setProgress = (p: SyncProgress) => store.set(p.jobId, p);
export const getProgress = (jobId: string) => store.get(jobId);
export const clearProgress = (jobId: string) => store.delete(jobId);
