import { readFile } from "node:fs/promises";
import { AppConfigSchema, type AppConfig } from "./schema.js";
import { validateConfig } from "./validator.js";
import { ConfigError } from "../utils/errors.js";
import logger from "../utils/logger.js";
export async function loadConfig(configPath: string): Promise<AppConfig> {
logger.info("Loading configuration", { path: configPath });
let rawContent: string;
try {
rawContent = await readFile(configPath, "utf-8");
} catch (err) {
throw new ConfigError(`Failed to read config file: ${configPath} - ${(err as Error).message}`);
}
let rawJson: unknown;
try {
rawJson = JSON.parse(rawContent);
} catch (err) {
throw new ConfigError(`Invalid JSON in config file: ${(err as Error).message}`);
}
const result = AppConfigSchema.safeParse(rawJson);
if (!result.success) {
const issues = result.error.issues.map(
(i) => ` - ${i.path.join(".")}: ${i.message}`
).join("\n");
throw new ConfigError(`Config validation failed:\n${issues}`);
}
const config = result.data;
validateConfig(config);
logger.info("Configuration loaded successfully", {
servers: Object.keys(config.servers).length,
groups: Object.keys(config.groups).length,
});
return config;
}