import type { Shoe } from "./shoe-database";

const HISTORY_KEY = "shoe_scan_history";

export function getHistory(): Shoe[] {
  if (typeof window === "undefined") {
    return [];
  }

  try {
    const historyJson = localStorage.getItem(HISTORY_KEY);
    if (historyJson) {
      return JSON.parse(historyJson) as Shoe[];
    }
  } catch (error) {
    console.error("Error reading history from localStorage", error);
  }
  return [];
}

export function addToHistory(shoe: Shoe): Shoe[] {
  if (typeof window === "undefined") {
    return [];
  }

  const currentHistory = getHistory();
  // Avoid adding duplicates
  if (currentHistory.some((item) => item.id === shoe.id)) {
    return currentHistory;
  }

  const newHistory = [shoe, ...currentHistory];
  // Limit history size if needed (e.g., to 20 items)
  // const limitedHistory = newHistory.slice(0, 20);

  try {
    localStorage.setItem(HISTORY_KEY, JSON.stringify(newHistory));
    return newHistory;
  } catch (error) {
    console.error("Error saving history to localStorage", error);
    return currentHistory; // Return original history on error
  }
}

export function clearHistory(): void {
  if (typeof window === "undefined") {
    return;
  }

  try {
    localStorage.removeItem(HISTORY_KEY);
  } catch (error) {
    console.error("Error clearing history from localStorage", error);
  }
}