// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: GPL-3.0-or-later

import { describe, test, expect, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { ConfigError } from "../src/util/errors.js";
import { loadConfig } from "../src/config/loader.js";

describe("loadConfig - ConfigError rethrown directly (issue #10)", () => {
  let configDir: string;
  let configPath: string;
  const originalEnv = { ...process.env };

  beforeEach(() => {
    configDir = mkdtempSync(join(tmpdir(), "rumilo-cfg-test10-"));
    const xdgBase = join(configDir, "xdg");
    const rumiloDir = join(xdgBase, "rumilo");
    mkdirSync(rumiloDir, { recursive: true });
    configPath = join(rumiloDir, "config.toml");
    process.env["XDG_CONFIG_HOME"] = xdgBase;
  });

  afterEach(() => {
    process.env = { ...originalEnv };
    try {
      rmSync(configDir, { recursive: true, force: true });
    } catch {}
  });

  test("ConfigError from validation is rethrown with original message and stack", async () => {
    // Write invalid config that triggers ConfigError from validatePartialConfig
    writeFileSync(configPath, `[defaults]\nmodel = 42\n`);
    try {
      await loadConfig();
      throw new Error("should have thrown");
    } catch (e: any) {
      expect(e).toBeInstanceOf(ConfigError);
      // The original message should include the validation details, not be re-wrapped
      expect(e.message).toContain("/defaults/model");
      // Stack should reference the validation function, not be a generic re-wrap
      expect(e.stack).toBeDefined();
    }
  });

  test("TOML parse error is wrapped as ConfigError with original message", async () => {
    writeFileSync(configPath, `[invalid toml !!!`);
    try {
      await loadConfig();
      throw new Error("should have thrown");
    } catch (e: any) {
      expect(e).toBeInstanceOf(ConfigError);
      // Should contain the original TOML parse error message
      expect(e.message.length).toBeGreaterThan(0);
    }
  });
});
