import log4js from "log4js";
import { loadConfig, saveConfig } from "./config.js";

export const VALID_LOG_LEVELS = ["trace", "debug", "info", "warn", "error"];

export async function applyLogLevel(level) {
  const normalized = String(level || "").toLowerCase();

  if (!VALID_LOG_LEVELS.includes(normalized)) {
    return {
      valid: false,
      error: `Invalid log level. Must be one of: ${VALID_LOG_LEVELS.join(", ")}`,
    };
  }

  const config = loadConfig();
  config.logLevel = normalized;
  await saveConfig(config);

  log4js.configure({
    appenders: { out: { type: "stdout" } },
    categories: { default: { appenders: ["out"], level: normalized } },
  });

  return { valid: true, logLevel: normalized };
}
