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

import { describe, test, expect, beforeAll, afterAll } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import simpleGit from "simple-git";
import { createGitLogTool } from "../src/agent/tools/git/log.js";
import { ToolInputError } from "../src/util/errors.js";

let workDir: string;
let git: ReturnType<typeof simpleGit>;

beforeAll(async () => {
  workDir = mkdtempSync(join(tmpdir(), "rumilo-gitlog-test-"));
  git = simpleGit(workDir);
  await git.init();
  await git.addConfig("user.name", "Test");
  await git.addConfig("user.email", "test@test.com");
  await git.addConfig("commit.gpgsign", "false");
  writeFileSync(join(workDir, "file.txt"), "hello");
  await git.add("file.txt");
  await git.commit("initial commit");
});

afterAll(() => {
  try {
    rmSync(workDir, { recursive: true, force: true });
  } catch {}
});

describe("git_log validation - dead code fix (issue #12)", () => {
  test("whitespace-only author throws ToolInputError", async () => {
    const tool = createGitLogTool(workDir);
    await expect(tool.execute("id", { author: "   " })).rejects.toThrow(ToolInputError);
  });

  test("empty-string author throws ToolInputError", async () => {
    const tool = createGitLogTool(workDir);
    await expect(tool.execute("id", { author: "" })).rejects.toThrow(ToolInputError);
  });

  test("empty-string since throws ToolInputError", async () => {
    const tool = createGitLogTool(workDir);
    await expect(tool.execute("id", { since: "  " })).rejects.toThrow(ToolInputError);
  });

  test("empty-string until throws ToolInputError", async () => {
    const tool = createGitLogTool(workDir);
    await expect(tool.execute("id", { until: "  " })).rejects.toThrow(ToolInputError);
  });

  test("valid author is accepted", async () => {
    const tool = createGitLogTool(workDir);
    // Should not throw
    const result: any = await tool.execute("id", { author: "Test" });
    expect(result.details.count).toBeGreaterThanOrEqual(1);
  });
});
