import { mkdirSync, existsSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
import { dirname } from "node:path";
import { randomBytes } from "node:crypto";
import { tokenFile } from "./paths";
import { CollectorFatalError } from "./errors";

export function loadOrCreateToken(): string {
  const path = tokenFile();
  if (existsSync(path)) {
    const contents = readFileSync(path, "utf8").trim();
    if (!contents) {
      throw new CollectorFatalError(
        "TOKEN_EMPTY",
        `token file ${path} exists but is empty`,
      );
    }
    return contents;
  }

  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
  const token = randomBytes(32).toString("hex");
  writeFileSync(path, token, { mode: 0o600 });
  chmodSync(path, 0o600);
  return token;
}
