import { describe, it, expect } from "vitest";
import { isSensitiveKey, redactValue, redactEnvVariables } from "./redact-utils.js";

describe("isSensitiveKey", () => {
  it.each([
    "ANTHROPIC_API_KEY",
    "OPENAI_API_KEY",
    "OPENROUTER_API_KEY",
    "LINEAR_API_KEY",
    "API_KEY",
    "api_key",
    "apiKey",
    "ApiKey",
    "MY_SECRET",
    "DB_PASSWORD",
    "AUTH_TOKEN",
    "CLAUDE_CODE_AUTH_TOKEN",
    "OAUTH_TOKEN",
    "PRIVATE_KEY",
    "AWS_SECRET_ACCESS_KEY",
    "GITHUB_TOKEN",
    "MY_CREDENTIAL",
  ])("returns true for sensitive key: %s", (key) => {
    expect(isSensitiveKey(key)).toBe(true);
  });

  it.each([
    "NODE_ENV",
    "PORT",
    "HOST",
    "DATABASE_URL",
    "LOG_LEVEL",
    "TZ",
    "PATH",
    "HOME",
    "ZENCODE_DIR",
  ])("returns false for non-sensitive key: %s", (key) => {
    expect(isSensitiveKey(key)).toBe(false);
  });
});

describe("redactValue", () => {
  it("returns empty string for empty value", () => {
    expect(redactValue("")).toBe("");
  });

  it("returns empty string for whitespace-only value", () => {
    expect(redactValue("   ")).toBe("");
  });

  it("returns **** for values 4 chars or shorter", () => {
    expect(redactValue("ab")).toBe("****");
    expect(redactValue("abcd")).toBe("****");
  });

  it("shows last 4 chars for longer values", () => {
    expect(redactValue("sk-ant-api03-abcdefgh")).toBe("****efgh");
  });

  it("trims before measuring length", () => {
    expect(redactValue("  ab  ")).toBe("****");
  });
});

describe("redactEnvVariables", () => {
  it("redacts sensitive keys and leaves others intact", () => {
    const input = {
      ANTHROPIC_API_KEY: "sk-ant-api03-abcdefgh",
      NODE_ENV: "production",
      PORT: "3000",
      MY_SECRET: "supersecret123",
    };
    const result = redactEnvVariables(input);
    expect(result).toEqual({
      ANTHROPIC_API_KEY: "****efgh",
      NODE_ENV: "production",
      PORT: "3000",
      MY_SECRET: "****t123",
    });
  });

  it("handles empty variables", () => {
    expect(redactEnvVariables({})).toEqual({});
  });

  it("handles empty sensitive values", () => {
    const result = redactEnvVariables({ API_KEY: "" });
    expect(result).toEqual({ API_KEY: "" });
  });
});
