import type { StateCreator } from "zustand";
import type { LessonPlanDocument } from "../types";
import type { EditorState } from "./use-lesson-plan-editor";

export interface VersionSlice {
  isDirty: boolean;
  isSaving: boolean;
  lastSavedAt: number | null;
  hydrate: (planId: string, title: string, doc: LessonPlanDocument) => void;
  markSaved: () => void;
  setSaving: (saving: boolean) => void;
  replaceDoc: (doc: LessonPlanDocument) => void;
}

export const createVersionSlice: StateCreator<
  EditorState,
  [],
  [],
  VersionSlice
> = (set) => ({
  isDirty: false,
  isSaving: false,
  lastSavedAt: null,

  hydrate: (planId, title, doc) =>
    set({
      planId,
      title,
      doc,
      isDirty: false,
      lastSavedAt: Date.now(),
      selectedNodeId: null,
    }),

  markSaved: () => set({ isDirty: false, lastSavedAt: Date.now() }),
  setSaving: (saving) => set({ isSaving: saving }),
  replaceDoc: (doc) => set({ doc, isDirty: false }),
});
