import { constants } from "node:fs";
import { lstat, open } from "node:fs/promises";

export async function provisionAccount({ accountHandle, provisioningDir }) {
  const source = accountHandle?.authPath;
  if (typeof source !== "string" || typeof provisioningDir !== "string") throw new Error("account-provision-invalid");
  const stat = await lstat(source);
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("account-auth-source-invalid");
  const input = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW);
  const output = await open(`${provisioningDir}/auth.json`, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
  try {
    await new Promise((resolveCopy, reject) => {
      const sourceStream = input.createReadStream();
      const targetStream = output.createWriteStream();
      sourceStream.once("error", reject);
      targetStream.once("error", reject);
      targetStream.once("finish", resolveCopy);
      sourceStream.pipe(targetStream);
    });
  } finally {
    await Promise.allSettled([input.close(), output.close()]);
  }
}
