// ─── ICLOUD Settings — baca/tulis dari JSON, fallback .env ─────────
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";

const __dirname = dirname(fileURLToPath(import.meta.url));
const SETTINGS_PATH = join(__dirname, "..", "data", "icloud-settings.json");

function defaultSettings() {
  return {
    apiUrl: process.env.ICLOUD_API_URL || "https://icloud.studiolabs.web.id",
    sessionToken: process.env.ICLOUD_SESSION_TOKEN || "",
    deviceId: process.env.ICLOUD_DEVICE_ID || "",
    accountId: process.env.ICLOUD_ACCOUNT_ID || "",
  };
}

export function loadIcloudSettings() {
  try {
    if (existsSync(SETTINGS_PATH)) {
      const raw = readFileSync(SETTINGS_PATH, "utf-8");
      const saved = JSON.parse(raw);
      return { ...defaultSettings(), ...saved };
    }
  } catch (_e) {}
  return defaultSettings();
}

export function saveIcloudSettings(newSettings) {
  const dir = dirname(SETTINGS_PATH);
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
  writeFileSync(SETTINGS_PATH, JSON.stringify(newSettings, null, 2), "utf-8");
  return loadIcloudSettings();
}

// Inisialisasi awal
const current = loadIcloudSettings();
if (current.sessionToken && !existsSync(SETTINGS_PATH)) {
  saveIcloudSettings(current);
  console.log("[ICLOUD] Settings diinisialisasi dari .env → data/icloud-settings.json");
}
