const test = require("node:test");
const assert = require("node:assert/strict");
const {
  editableSessionPayload,
  draftChanges,
  approvalChanges,
  shareChanges,
  unshareChanges,
} = require("../src/security/sessionLifecycle");

test("session edits return shared content to private draft", () => {
  const changes = draftChanges({ revision: 2 }, {
    title: "Synthetic session",
    shared_client_notes: "Approved-safe draft",
    privateFieldFromBrowser: "blocked",
    status: "shared",
  }, "coach-a");

  assert.equal(changes.status, "draft");
  assert.equal(changes.revision, 3);
  assert.equal(changes.approved_at, null);
  assert.equal(changes.privateFieldFromBrowser, undefined);
});

test("approval requires client-safe notes", () => {
  assert.throws(() => approvalChanges({ shared_client_notes: "" }, "coach-a"));
  const changes = approvalChanges({ shared_client_notes: "Safe notes" }, "coach-a", new Date(0));
  assert.equal(changes.status, "approved");
  assert.equal(changes.approved_at.getTime(), 0);
});

test("only approved sessions can be shared", () => {
  assert.throws(() => shareChanges({ status: "draft" }, "coach-a"));
  assert.equal(shareChanges({ status: "approved" }, "coach-a").status, "shared");
});

test("unsharing removes portal visibility state", () => {
  const changes = unshareChanges("coach-a", new Date(0));
  assert.equal(changes.status, "unshared");
  assert.equal(changes.unshared_at.getTime(), 0);
});

test("editable payload ignores ownership and lifecycle fields", () => {
  const payload = editableSessionPayload({ title: "Allowed", clientId: "blocked", approved_by_id: "blocked" });
  assert.deepEqual(payload, { title: "Allowed" });
});
