import { describe, expect, it } from "vitest";
import type { TenantSummary } from "../../../lib/adminApi";
import {
  filterTenantsByScope,
  getTenantSearchMatchIds,
  getTenantViewRows,
  resolveTenantSelectionIds,
  tenantMatchesListSearch,
} from "./tenantListView";

function tenant(
  id: string,
  name: string,
  slug: string,
  parentId?: string,
): TenantSummary {
  return {
    id,
    name,
    slug,
    parentId,
    type: parentId ? "ORGANIZATION" : "COMPANY",
    description: "",
    status: "active",
    memberCount: 0,
    createdAt: "",
    updatedAt: "",
  };
}

const tenants = [
  tenant("company-1", "한맥기술", "hanmac"),
  tenant("dept-1", "기술기획", "planning", "company-1"),
  tenant("team-1", "플랫폼팀", "platform", "dept-1"),
  tenant("company-2", "삼안", "saman"),
];

describe("TenantListPage tenant list helpers", () => {
  it("selects a parent tenant together with every descendant", () => {
    expect(
      resolveTenantSelectionIds({
        currentIds: [],
        tenant: tenants[0],
        checked: true,
        tenants,
        deletableTenants: tenants,
      }),
    ).toEqual(["company-1", "dept-1", "team-1"]);
  });

  it("removes a parent tenant together with every descendant", () => {
    expect(
      resolveTenantSelectionIds({
        currentIds: ["company-1", "dept-1", "team-1", "company-2"],
        tenant: tenants[0],
        checked: false,
        tenants,
        deletableTenants: tenants,
      }),
    ).toEqual(["company-2"]);
  });

  it("filters to descendants of the selected scope tenant", () => {
    expect(
      filterTenantsByScope(tenants, "company-1").map((item) => item.id),
    ).toEqual(["dept-1", "team-1"]);
  });

  it("searches tenants by name, slug, and UUID", () => {
    expect(tenantMatchesListSearch(tenants[2], "team-1")).toBe(true);
    expect(tenantMatchesListSearch(tenants[2], "platform")).toBe(true);
    expect(tenantMatchesListSearch(tenants[2], "플랫폼")).toBe(true);
    expect(tenantMatchesListSearch(tenants[2], "삼안")).toBe(false);
  });

  it("can return tree rows or same-level table rows", () => {
    expect(getTenantViewRows(tenants, "tree").map((row) => row.depth)).toEqual([
      0, 1, 2, 0,
    ]);
    expect(getTenantViewRows(tenants, "table").map((row) => row.depth)).toEqual(
      [0, 0, 0, 0],
    );
  });

  it("marks only direct search matches when tree search includes ancestors", () => {
    const treeRows = getTenantViewRows(
      tenants.filter((item) => item.id !== "company-2"),
      "tree",
      "",
      true,
    );

    expect(treeRows.map((row) => row.id)).toEqual([
      "company-1",
      "dept-1",
      "team-1",
    ]);
    expect(getTenantSearchMatchIds(treeRows, "platform")).toEqual(["team-1"]);
  });
});
