/**
 * Shared config and row builders for Groups B2CDataTable on all three pages:
 * Settings → Groups (global), Company → Groups, Project → Groups.
 * Columns: Type, Naam, Beschrijving, Bron, Modules, Leden, Acties.
 * No backend or permission logic changes; UI only.
 */

/** Bron display labels: where the group was created (global / company / project). */
export const BRON_LABEL_GLOBAL = "Global group";
export const BRON_LABEL_COMPANY = "Company group";
export const BRON_LABEL_PROJECT = "Project group";

function getBronLabelFromScopeType(scopeType) {
  if (scopeType === "global") return BRON_LABEL_GLOBAL;
  if (scopeType === "company") return BRON_LABEL_COMPANY;
  if (scopeType === "project") return BRON_LABEL_PROJECT;
  return "—";
}

/**
 * Count distinct modules from permission names (object keys or array of names).
 * Permission format: scope.module.action (e.g. company.dashboard.view) → module = dashboard.
 */
export function countModulesFromPermissions(permissions) {
  if (
    !permissions ||
    (typeof permissions !== "object" && !Array.isArray(permissions))
  )
    return 0;
  const names = Array.isArray(permissions)
    ? permissions.filter((n) => typeof n === "string" && n.includes("."))
    : Object.keys(permissions).filter(
        (k) => permissions[k] && typeof k === "string" && k.includes("."),
      );
  const modules = new Set();
  names.forEach((name) => {
    const parts = name.trim().split(".");
    if (parts.length >= 2) modules.add(parts[1]);
  });
  return modules.size;
}

/**
 * Format module count for display: "0 modules", "1 module", "X modules".
 */
export function formatModuleCount(count) {
  if (count === 0) return "0 modules";
  if (count === 1) return "1 module";
  return `${count} modules`;
}

/**
 * Resolve bron label for a group (global Settings page): Global group / Company group / Project group.
 */
export function resolveBronForGroup(group) {
  if (!group?.scope_type) return { bron_label: "—", bron_variant: "neutral" };
  return {
    bron_label: getBronLabelFromScopeType(group.scope_type),
    bron_variant:
      group.scope_type === "global"
        ? "global"
        : group.scope_type === "company"
          ? "company"
          : "project",
  };
}

/**
 * Resolve bron label for an actor (group) on company or project page.
 * Own group → current scope (Company group / Project group). Inherited → source_scope_type.
 */
export function resolveBronForActor(actor, viewScope) {
  if (!actor) return { bron_label: "—", bron_variant: "neutral" };
  const scopeType = actor.is_inherited
    ? (actor.source_scope_type ?? viewScope)
    : viewScope;
  return {
    bron_label: getBronLabelFromScopeType(scopeType),
    bron_variant:
      scopeType === "global"
        ? "global"
        : scopeType === "company"
          ? "company"
          : "project",
  };
}

/**
 * Build B2CDataTable row from global groups API item.
 */
export function buildRowFromGroup(group, viewScope = "global") {
  const companyPerms = group.companyPermissions || {};
  const projectPerms = group.projectPermissions || {};
  const companyNames =
    typeof companyPerms === "object"
      ? Object.keys(companyPerms).filter((k) => companyPerms[k])
      : [];
  const projectNames =
    typeof projectPerms === "object"
      ? Object.keys(projectPerms).filter((k) => projectPerms[k])
      : [];
  const allNames = [...companyNames, ...projectNames];
  const count = countModulesFromPermissions(allNames.length ? allNames : {});
  const { bron_label, bron_variant } = resolveBronForGroup(group);
  return {
    id: `group-${group.id}`,
    type: "group",
    type_label: "Groep",
    naam: group.name ?? "",
    beschrijving: group.description ?? "",
    company_name: group.company_name ?? "—",
    project_name: group.project_name ?? "—",
    bron_label,
    bron_variant,
    bron_search: bron_label,
    modules_count: count,
    modules_text: formatModuleCount(count),
    leden: group.members_count ?? 0,
    _raw: group,
    _is_inherited: false,
  };
}

/**
 * Build B2CDataTable row from actor (group or user) on company/project page.
 */
export function buildRowFromActor(actor, viewScope) {
  if (actor.actor_type === "user") {
    const perms = actor.permissions || {};
    const count = countModulesFromPermissions(perms);
    return {
      id: `user-${actor.actor_id}-${actor.membership_id ?? actor.actor_id}`,
      type: "user",
      type_label: "Gebruiker",
      naam: actor.display_name ?? "",
      beschrijving: "—",
      company_name: actor.company_name ?? "—",
      project_name: actor.project_name ?? "—",
      bron_label: "—",
      bron_variant: "neutral",
      bron_search: "—",
      modules_count: count,
      modules_text: formatModuleCount(count),
      leden: "—",
      _raw: actor,
      _is_inherited: false,
    };
  }
  const { bron_label, bron_variant } = resolveBronForActor(actor, viewScope);
  const count = countModulesFromPermissions(actor.permissions);
  return {
    id: `group-${actor.actor_id}`,
    type: "group",
    type_label: "Groep",
    naam: actor.display_name ?? "",
    beschrijving: actor.description ?? "—",
    company_name: actor.company_name ?? "—",
    project_name: actor.project_name ?? "—",
    bron_label,
    bron_variant,
    bron_search: bron_label,
    modules_count: count,
    modules_text: formatModuleCount(count),
    leden: actor.members_count ?? 0,
    _raw: actor,
    _is_inherited: actor.is_inherited ?? false,
  };
}

/** B2CDataTable column definitions for groups tables (all pages). Type and Bron use custom cell slots. */
export const GROUPS_TABLE_COLUMNS = [
  {
    key: "type",
    header: "Type",
    searchable: true,
    filterable: true,
    defaultVisible: true,
  },
  {
    key: "naam",
    header: "Naam",
    searchable: true,
    filterable: true,
    defaultVisible: true,
  },
  {
    key: "beschrijving",
    header: "Beschrijving",
    searchable: true,
    filterable: true,
    defaultVisible: true,
  },
  {
    key: "company_name",
    header: "Bedrijf",
    searchable: true,
    filterable: true,
    defaultVisible: true,
  },
  {
    key: "project_name",
    header: "Project",
    searchable: true,
    filterable: true,
    defaultVisible: true,
  },
  {
    key: "bron",
    header: "Bron",
    searchable: true,
    filterable: true,
    defaultVisible: true,
    filterKey: "bron_search",
  },
  {
    key: "modules_text",
    header: "Modules",
    searchable: false,
    filterable: true,
    defaultVisible: true,
  },
  {
    key: "leden",
    header: "Leden",
    type: "text",
    searchable: false,
    filterable: true,
    defaultVisible: true,
  },
  {
    key: "actions",
    header: "Acties",
    searchable: false,
    filterable: false,
    defaultVisible: true,
    sortable: false,
  },
];
