import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { randomBytes } from "node:crypto";
import { configDir, ControllerFatalError } from "./config";

export function tokenFile(): string {
  return join(configDir(), "token");
}

export function loadOrCreateToken(): string {
  const path = tokenFile();
  if (existsSync(path)) {
    const contents = readFileSync(path, "utf8").trim();
    if (!contents) {
      throw new ControllerFatalError(
        "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;
}
