import { join, dirname } from "node:path";
import {
  mkdir,
  writeFile,
  readFile,
  unlink,
  rename
} from "node:fs/promises";
import { existsSync } from "node:fs";
import { randomBytes } from "node:crypto";
import {
  keychainAvailable,
  keychainSet,
  keychainGet,
  keychainDelete,
  WIGOLO_SERVICE
} from "../../../security/keychain.js";
const KEYCHAIN_USER = "tui";
const FILE_MODE = 384;
const DIR_MODE = 448;
function keychainAccount(key) {
  return `${WIGOLO_SERVICE}-tui-${key}`;
}
function filePath(dataDir, key) {
  return join(dataDir, "keys", key);
}
async function atomicWriteFile(target, data) {
  const dir = dirname(target);
  await mkdir(dir, { recursive: true, mode: DIR_MODE });
  const tmp = join(dir, `.tmp.${process.pid}.${randomBytes(6).toString("hex")}`);
  await writeFile(tmp, data, { mode: FILE_MODE });
  try {
    await rename(tmp, target);
  } catch (err) {
    try {
      await unlink(tmp);
    } catch {
    }
    throw err;
  }
}
function defaultSecretStore(opts) {
  return {
    async set(key, value) {
      if (keychainAvailable()) {
        try {
          keychainSet(keychainAccount(key), KEYCHAIN_USER, value);
          return { location: "keychain" };
        } catch {
        }
      }
      await atomicWriteFile(filePath(opts.dataDir, key), value);
      return { location: "file" };
    },
    async get(key) {
      if (keychainAvailable()) {
        const v = keychainGet(keychainAccount(key), KEYCHAIN_USER);
        if (v !== null && v.length > 0) return v;
      }
      const path = filePath(opts.dataDir, key);
      if (!existsSync(path)) return null;
      try {
        return await readFile(path, "utf-8");
      } catch {
        return null;
      }
    },
    async remove(key) {
      if (keychainAvailable()) {
        try {
          keychainDelete(keychainAccount(key), KEYCHAIN_USER);
        } catch {
        }
      }
      const path = filePath(opts.dataDir, key);
      if (existsSync(path)) {
        try {
          await unlink(path);
        } catch {
        }
      }
    }
  };
}
export {
  defaultSecretStore
};
//# sourceMappingURL=secret-store.js.map