import { readFileSync, rmSync, writeFileSync } from "node:fs";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { kanboardEnvFile, loadIncidentsConnection } from "./connection";

describe("loadIncidentsConnection", () => {
  let previousConfigDir: string | undefined;
  let dir: string;

  beforeEach(() => {
    previousConfigDir = process.env.OVERDECK_CONFIG_DIR;
    dir = mkdtempSync(join(tmpdir(), "overdeck-incident-connection-"));
    process.env.OVERDECK_CONFIG_DIR = dir;
  });

  afterEach(() => {
    if (previousConfigDir === undefined) {
      delete process.env.OVERDECK_CONFIG_DIR;
    } else {
      process.env.OVERDECK_CONFIG_DIR = previousConfigDir;
    }
    rmSync(dir, { recursive: true, force: true });
  });

  test("returns null when kanboard env is missing", () => {
    expect(loadIncidentsConnection()).toBeNull();
  });

  test("returns null when api token is missing", () => {
    const tokenFile = kanboardEnvFile();
    writeFileSync(tokenFile, "FOO=bar\n# ignore\n", { mode: 0o600 });

    expect(loadIncidentsConnection()).toBeNull();
  });

  test("reads token and defaults baseUrl", () => {
    const tokenFile = kanboardEnvFile();
    writeFileSync(tokenFile, "KANBOARD_API_TOKEN='secret-token'\n", { mode: 0o600 });

    const connection = loadIncidentsConnection();
    expect(connection).not.toBeNull();
    expect(connection?.token).toBe("secret-token");
    expect(connection?.baseUrl).toBe("http://127.0.0.1:31339/jsonrpc.php");
    expect(readFileSync(tokenFile, "utf8")).toContain("KANBOARD_API_TOKEN='secret-token'");
  });
});
