import fs from "fs";
import path from "path";
import os from "os";
import { afterEach, describe, expect, it } from "vitest";
import { resolveDalBinary, resolveK6Binary } from "./index.mjs";

const originalK6Bin = process.env.TESTKIT_K6_BIN;

afterEach(() => {
  if (originalK6Bin === undefined) {
    delete process.env.TESTKIT_K6_BIN;
  } else {
    process.env.TESTKIT_K6_BIN = originalK6Bin;
  }
});

describe("config-index", () => {
  it("resolves the bundled k6 binary from the package root", () => {
    const binaryPath = resolveK6Binary();
    expect(path.basename(binaryPath)).toBe("k6");
    expect(fs.existsSync(binaryPath)).toBe(true);
  });

  it("keeps resolveDalBinary aligned with the shared k6 resolver", () => {
    expect(resolveDalBinary()).toBe(resolveK6Binary());
  });

  it("uses TESTKIT_K6_BIN when provided with a relative path", () => {
    const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "testkit-k6-"));
    const binPath = path.join(tempDir, "k6-custom");
    fs.writeFileSync(binPath, "#!/usr/bin/env bash\nexit 0\n");
    process.env.TESTKIT_K6_BIN = path.relative(process.cwd(), binPath);

    expect(resolveK6Binary()).toBe(binPath);
  });

  it("throws a clear error when TESTKIT_K6_BIN points at a missing path", () => {
    process.env.TESTKIT_K6_BIN = "./definitely-missing-k6-bin";

    expect(() => resolveK6Binary()).toThrow(
      /TESTKIT_K6_BIN points to a missing file/
    );
  });
});
