// store.js — JSON file persistence layer for todos.
// Keeps all data in a single JSON file under the user's home directory.

import fs from "node:fs";
import path from "node:path";
import os from "node:os";

const DEFAULT_DATA_DIR = path.join(os.homedir(), ".todo-cli");
const DEFAULT_DATA_FILE = "todos.json";

/**
 * Create a store backed by a JSON file.
 * @param {object} [opts]
 * @param {string} [opts.dataDir]  Directory for the data file.
 * @param {string} [opts.dataFile] Filename inside the data dir.
 */
export function createStore(opts = {}) {
  const dataDir = opts.dataDir ?? DEFAULT_DATA_DIR;
  const dataFile = opts.dataFile ?? DEFAULT_DATA_FILE;
  const filePath = path.join(dataDir, dataFile);

  function ensureDir() {
    if (!fs.existsSync(dataDir)) {
      fs.mkdirSync(dataDir, { recursive: true });
    }
  }

  /** Load all todos from disk. Returns [] when the file does not exist. */
  function load() {
    if (!fs.existsSync(filePath)) return [];
    try {
      const raw = fs.readFileSync(filePath, "utf8");
      const parsed = JSON.parse(raw);
      return Array.isArray(parsed) ? parsed : [];
    } catch {
      // Corrupt file — start fresh rather than crashing.
      return [];
    }
  }

  /** Persist the todos array to disk. */
  function save(todos) {
    ensureDir();
    fs.writeFileSync(filePath, JSON.stringify(todos, null, 2), "utf8");
  }

  return { load, save, filePath };
}