import { test } from "node:test";
import assert from "node:assert/strict";
import { pendingHolderMismatch } from "@/features/trainer/holderReviewMismatch";
import apiClient from "@/lib/api/client";
import { getOwnPlatformFee } from "@/features/profile/services/platformFee";

test("an approved holder no longer counts as a pending mismatch", () => {
  assert.equal(pendingHolderMismatch("approved", true), false);
});

test("a pending or rejected review keeps the server's mismatch flag", () => {
  assert.equal(pendingHolderMismatch("pending", true), true);
  assert.equal(pendingHolderMismatch("rejected", true), true);
  assert.equal(pendingHolderMismatch(null, true), true);
  assert.equal(pendingHolderMismatch("not_required", false), false);
  assert.equal(pendingHolderMismatch(undefined, undefined), undefined);
});

async function withStubbedGet<T>(rate: unknown, run: (calls: string[]) => Promise<T>): Promise<T> {
  const calls: string[] = [];
  const original = apiClient.get;
  (apiClient as unknown as { get: unknown }).get = async (url: string) => {
    calls.push(url);
    return { data: { data: { platform_fee_percentage: rate } } };
  };
  try {
    return await run(calls);
  } finally {
    (apiClient as unknown as { get: unknown }).get = original;
  }
}

test("the commission rate comes from the profile endpoint that carries it", async () => {
  await withStubbedGet("25.00", async (calls) => {
    assert.equal(await getOwnPlatformFee("organization"), "25.00");
    assert.equal(await getOwnPlatformFee("voluntary_team"), "25.00", "a team session type reads the organization profile");
    assert.deepEqual(calls, ["/organization-profile/", "/organization-profile/"]);
  });
  await withStubbedGet(0, async (calls) => {
    assert.equal(await getOwnPlatformFee("individual"), 0, "an own 0% override is a real rate, not missing");
    assert.equal(await getOwnPlatformFee("volunteer"), 0);
    assert.deepEqual(calls, ["/volunteer-profile/", "/volunteer-profile/"]);
  });
  await withStubbedGet(undefined, async () => {
    assert.equal(await getOwnPlatformFee("individual"), null, "a profile that does not send it gives null");
  });
});
