import { existsSync } from "node:fs";
import path from "node:path";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { Utils } from "electrobun/bun";

const AUTH_SERVICE = "com.tombutcher.farmcontrol";
const AUTH_SECRET_NAME = "authSession";
const SETTINGS_FILE = "settings.json";

function getSettingsPath() {
  return path.join(Utils.paths.userData, SETTINGS_FILE);
}

async function ensureUserDataDir() {
  await mkdir(Utils.paths.userData, { recursive: true });
}

export async function getAuthSession() {
  try {
    const value = await Bun.secrets.get({
      service: AUTH_SERVICE,
      name: AUTH_SECRET_NAME,
    });
    if (!value) return null;
    return JSON.parse(value);
  } catch (error) {
    console.warn("[auth-session] Failed to read auth session.", error);
    return null;
  }
}

export async function setAuthSession(session) {
  if (!session || typeof session !== "object") return false;

  try {
    await Bun.secrets.set({
      service: AUTH_SERVICE,
      name: AUTH_SECRET_NAME,
      value: JSON.stringify(session),
    });
    return true;
  } catch (error) {
    console.warn("[auth-session] Failed to write auth session.", error);
    return false;
  }
}

export async function clearAuthSession() {
  try {
    await Bun.secrets.delete({
      service: AUTH_SERVICE,
      name: AUTH_SECRET_NAME,
    });
    return true;
  } catch (error) {
    console.warn("[auth-session] Failed to clear auth session.", error);
    return false;
  }
}

export async function getAppSettings() {
  try {
    await ensureUserDataDir();
    const settingsPath = getSettingsPath();
    if (!existsSync(settingsPath)) return {};
    const raw = await readFile(settingsPath, "utf8");
    const settings = JSON.parse(raw);
    return settings && typeof settings === "object" ? settings : {};
  } catch (error) {
    console.warn("[app-settings] Failed to read settings.", error);
    return {};
  }
}

export async function setAppSettings(settings) {
  if (!settings || typeof settings !== "object") return false;

  try {
    await ensureUserDataDir();
    await writeFile(getSettingsPath(), JSON.stringify(settings, null, 2));
    return true;
  } catch (error) {
    console.warn("[app-settings] Failed to write settings.", error);
    return false;
  }
}
