import { CreateProjectInputs } from "../api/projects/actions";

const STORAGE_KEY = "draftProjects";

const getStorage = (): {
  [draftId: string]: CreateProjectInputs;
} => {
  if (typeof window === "undefined") {
    return {};
  }

  const storageString = localStorage.getItem(STORAGE_KEY);
  if (!storageString) {
    return {};
  }

  try {
    return JSON.parse(storageString);
  } catch {
    return {};
  }
};

export const loadDrafts = (): [id: string, inputs: CreateProjectInputs][] => {
  return Object.entries(getStorage());
};

export const saveToLocalStorage = (
  draftId: number,
  data: CreateProjectInputs,
) => {
  const storage = getStorage();
  localStorage.setItem(
    STORAGE_KEY,
    JSON.stringify({
      ...storage,
      [draftId]: data,
    }),
  );
};

export const loadDraft = (draftId: number): CreateProjectInputs | undefined => {
  const storage = getStorage();
  const draft = storage[draftId];

  return draft;
};

export const deleteDraft = (draftId: number) => {
  const storage = getStorage();

  delete storage[draftId];

  localStorage.setItem(STORAGE_KEY, JSON.stringify(storage));
};
