import type { TenantSummary } from "../../lib/adminApi";

export function getTenantVisibility(tenant: Pick<TenantSummary, "config">) {
  const raw = String(tenant.config?.visibility ?? "public").toLowerCase();
  if (raw === "internal" || raw === "private") return raw;
  return "public";
}

export function filterTenantsByVisibility(
  tenants: TenantSummary[],
  mode: "internal" | "public",
) {
  const excludedIds = new Set<string>();
  for (const tenant of tenants) {
    const visibility = getTenantVisibility(tenant);
    if (
      visibility === "private" ||
      (mode === "public" && visibility === "internal")
    ) {
      excludedIds.add(tenant.id);
    }
  }

  let changed = true;
  while (changed) {
    changed = false;
    for (const tenant of tenants) {
      if (
        tenant.parentId &&
        excludedIds.has(tenant.parentId) &&
        !excludedIds.has(tenant.id)
      ) {
        excludedIds.add(tenant.id);
        changed = true;
      }
    }
  }

  return tenants.filter((tenant) => !excludedIds.has(tenant.id));
}

export function getOrgUnitType(config: Record<string, unknown> | undefined) {
  const value = config?.orgUnitType;
  return typeof value === "string" ? value.trim() : "";
}
