/**
 * Project path storage using localStorage
 * Mirrors pattern from lib/auth/api-key.ts
 */

const STORAGE_KEY = "aphoria-project-path";
const DEFAULT_PATH = "/home/jml/Workspace/stemedb"; // Fallback default

/**
 * Get project path from localStorage or environment variable
 * Server-safe: returns env var or default when window is undefined
 */
export function getProjectPath(): string {
  if (typeof window === "undefined") {
    return process.env.NEXT_PUBLIC_DEFAULT_PROJECT_PATH || DEFAULT_PATH;
  }
  return (
    localStorage.getItem(STORAGE_KEY) ||
    process.env.NEXT_PUBLIC_DEFAULT_PROJECT_PATH ||
    DEFAULT_PATH
  );
}

/**
 * Save project path to localStorage
 */
export function setProjectPath(path: string): void {
  if (typeof window === "undefined") return;

  const trimmedPath = path.trim();
  if (trimmedPath) {
    localStorage.setItem(STORAGE_KEY, trimmedPath);
  }
}

/**
 * Clear project path from localStorage
 */
export function clearProjectPath(): void {
  if (typeof window === "undefined") return;
  localStorage.removeItem(STORAGE_KEY);
}

/**
 * Check if project path is set (not default)
 */
export function hasCustomProjectPath(): boolean {
  if (typeof window === "undefined") return false;
  const stored = localStorage.getItem(STORAGE_KEY);
  return stored !== null && stored !== DEFAULT_PATH;
}
