import assert from "node:assert/strict";
import { describe, it } from "node:test";

import { collectOrganizationEmployees, countOrganizationEmployees } from "./orgTreeEmployees.js";

describe("organization tree employee aggregation", () => {
  it("collects employees from the selected organization and all descendant organizations", () => {
    const branch = {
      node_id: 10,
      node_type: "BRANCH",
      node_label: "旭升车间",
      employees: [
        { employee_id: 1, employee_name: "直属主管", mobile: "13000000001" }
      ],
      children: [
        {
          node_id: 11,
          node_type: "DEPARTMENT",
          node_label: "旭升加工部",
          employees: [
            { employee_id: 2, employee_name: "张三", mobile: "13000000002" },
            { employee_id: 3, employee_name: "李四", mobile: "13000000003" }
          ],
          children: [
            {
              node_id: 12,
              node_type: "GROUP",
              node_label: "冲压小组",
              employees: [
                { employee_id: 4, employee_name: "王五", mobile: "13000000004" }
              ]
            }
          ]
        }
      ]
    };

    const employees = collectOrganizationEmployees(branch);

    assert.deepEqual(employees.map((employee) => employee.employee_name), ["直属主管", "张三", "李四", "王五"]);
    assert.equal(employees[1].parent_node_id, 11);
    assert.equal(employees[1].parent_node_label, "旭升加工部");
    assert.deepEqual(employees[1].organization_path_parts, ["旭升车间", "旭升加工部"]);
    assert.equal(employees[1].organization_path, "旭升车间 / 旭升加工部");
    assert.equal(employees[3].organization_path, "旭升车间 / 旭升加工部 / 冲压小组");
    assert.equal(countOrganizationEmployees(branch), 4);
  });

  it("deduplicates employees that appear in multiple descendant branches", () => {
    const employee = { employee_id: 9, employee_name: "重复人员", mobile: "13000000009" };
    const branch = {
      node_id: 20,
      node_type: "BRANCH",
      node_label: "嘉恒车间",
      employees: [employee],
      children: [
        {
          node_id: 21,
          node_type: "DEPARTMENT",
          node_label: "嘉恒生产部",
          employees: [employee]
        }
      ]
    };

    const employees = collectOrganizationEmployees(branch);

    assert.equal(employees.length, 1);
    assert.equal(countOrganizationEmployees(branch), 1);
  });
});
