const STORAGE_KEY = "ben-to.recipe-checklist";

export type RecipeChecklistStored = Readonly<{
  ingredientIds: readonly string[];
  stepIds: readonly string[];
}>;

type RecipeChecklistMap = Record<string, RecipeChecklistStored>;

const emptyEntry = (): RecipeChecklistStored =>
  Object.freeze({ ingredientIds: Object.freeze([]), stepIds: Object.freeze([]) });

const loadMap = (): RecipeChecklistMap => {
  if (typeof localStorage === "undefined") return {};
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return {};
    const parsed = JSON.parse(raw) as unknown;
    if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {};
    return parsed as RecipeChecklistMap;
  } catch {
    return {};
  }
};

const saveMap = (map: RecipeChecklistMap): void => {
  if (typeof localStorage === "undefined") return;
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(map));
  } catch {
    /* quota / private mode */
  }
};

export const loadRecipeChecklist = (recipeKey: string): RecipeChecklistStored => {
  const map = loadMap();
  const entry = map[recipeKey];
  if (!entry || !Array.isArray(entry.ingredientIds) || !Array.isArray(entry.stepIds)) {
    return emptyEntry();
  }
  return Object.freeze({
    ingredientIds: Object.freeze([...entry.ingredientIds]),
    stepIds: Object.freeze([...entry.stepIds])
  });
};

export const saveRecipeChecklist = (recipeKey: string, data: RecipeChecklistStored): void => {
  const map = loadMap();
  map[recipeKey] = Object.freeze({
    ingredientIds: Object.freeze([...data.ingredientIds]),
    stepIds: Object.freeze([...data.stepIds])
  });
  saveMap(map);
};
