import test from "node:test";
import assert from "node:assert/strict";
import { createMessageAttemptTracker, createNewChatAttempt } from "./idempotent-action.js";

test("message attempts keep their key only for an uncertain retry of the same payload", () => {
  const ids = [
    "11111111-1111-4111-8111-111111111111",
    "22222222-2222-4222-8222-222222222222",
    "33333333-3333-4333-8333-333333333333"
  ];
  const tracker = createMessageAttemptTracker(() => ids.shift());
  const payload = { text: "Run once", options: { permissionProfile: ":workspace" } };

  const first = tracker.begin(payload);
  tracker.failed(first, new Error("pc_unreachable"));
  assert.equal(tracker.begin({ ...payload }), first);

  const edited = tracker.begin({ ...payload, text: "Run a new action" });
  assert.notEqual(edited, first);
  tracker.succeeded(edited);
  assert.notEqual(tracker.begin({ ...payload, text: "Run a new action" }), edited);
});

test("definite message failures do not reuse the previous action key", () => {
  const ids = [
    "44444444-4444-4444-8444-444444444444",
    "55555555-5555-4555-8555-555555555555"
  ];
  const tracker = createMessageAttemptTracker(() => ids.shift());
  const payload = { text: "Rejected" };
  const first = tracker.begin(payload);
  tracker.failed(first, new Error("session_busy"));
  assert.notEqual(tracker.begin(payload), first);
});

test("new chat retries retain separate session and message identities", () => {
  const ids = [
    "66666666-6666-4666-8666-666666666666",
    "77777777-7777-4777-8777-777777777777"
  ];
  const attempt = createNewChatAttempt(() => ids.shift());

  assert.equal(attempt.clientSessionId, "66666666-6666-4666-8666-666666666666");
  assert.equal(attempt.clientMessageId, "77777777-7777-4777-8777-777777777777");
});
