/**
 * The point of `describeRequestError` is what it leaves out.
 *
 * An axios rejection carries `config.data` (the serialized request body — the
 * password on the login path) and `config.headers` (`Authorization: Token …`).
 * These tests assert the summary keeps the diagnostic fields and drops
 * everything that could carry a credential, so a future "just log the whole
 * error, it's easier" change fails here.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";

import { describeRequestError } from "@/lib/api/logError";

/** Shaped like a real axios rejection from `POST /login/`. */
const loginRejection = {
  message: "Request failed with status code 401",
  name: "AxiosError",
  config: {
    url: "/login/",
    method: "post",
    data: JSON.stringify({ email: "a@b.com", password: "s3cret-passw0rd" }),
    headers: { Authorization: "Token abc123def456", "x-lang": "en" },
  },
  request: { responseURL: "https://api.example.com/login/" },
  response: {
    status: 401,
    data: { msg: "Invalid credentials", key: "fail" },
  },
};

describe("describeRequestError", () => {
  test("keeps the status and the server message", () => {
    const summary = describeRequestError(loginRejection);
    assert.equal(summary.status, 401);
    assert.equal(summary.msg, "Invalid credentials");
    assert.equal(summary.message, "Request failed with status code 401");
  });

  test("returns ONLY those three keys — no config, no request, no response", () => {
    assert.deepEqual(Object.keys(describeRequestError(loginRejection)).sort(), [
      "message",
      "msg",
      "status",
    ]);
  });

  test("the password cannot appear anywhere in the serialized summary", () => {
    const serialized = JSON.stringify(describeRequestError(loginRejection));
    assert.ok(!serialized.includes("s3cret-passw0rd"));
    assert.ok(!serialized.includes("password"));
    assert.ok(!serialized.includes("a@b.com"));
  });

  test("the auth token cannot appear either", () => {
    const serialized = JSON.stringify(describeRequestError(loginRejection));
    assert.ok(!serialized.includes("abc123def456"));
    assert.ok(!serialized.includes("Authorization"));
  });

  test("a plain Error keeps its message and nothing else", () => {
    assert.deepEqual(describeRequestError(new Error("offline")), {
      message: "offline",
    });
  });

  test("a string, null and undefined are handled without throwing", () => {
    assert.deepEqual(describeRequestError("boom"), { message: "boom" });
    assert.deepEqual(describeRequestError(null), {});
    assert.deepEqual(describeRequestError(undefined), {});
  });

  test("a non-string msg is dropped rather than passed through", () => {
    const summary = describeRequestError({
      response: { status: 500, data: { msg: { en: "x", ar: "y" } } },
    });
    assert.equal(summary.status, 500);
    assert.equal(summary.msg, undefined);
  });
});
