'use client';

import { CheckboxTree } from '@/components/ui/tree';
import type { PermissionTreeItem, PermissionTreeNode } from '@/types';

export function mapPermissionTree(
  nodes: PermissionTreeNode[],
): PermissionTreeItem[] {
  return nodes.map((node) => ({
    id: node.id,
    key: node.slug || node.name,
    label: node.display_name || node.name,
    description: node.description,
    type: node.type,
    isGrantedByDefault: Boolean(node.is_granted_by_default),
    children: mapPermissionTree(node.children || []),
  }));
}

export function collectDefaultPermissionIds(
  nodes: PermissionTreeItem[],
): number[] {
  return nodes.flatMap((node) => [
    ...(node.isGrantedByDefault ? [node.id] : []),
    ...collectDefaultPermissionIds(node.children),
  ]);
}

export function collectPermissionIdsByKeys(
  nodes: PermissionTreeItem[],
  keys: string[],
): number[] {
  const selectedKeys = new Set(keys);
  return nodes.flatMap((node) => [
    ...(selectedKeys.has(node.key) ? [node.id] : []),
    ...collectPermissionIdsByKeys(node.children, keys),
  ]);
}

export function PermissionTree({
  items,
  selectedIds,
  onChange,
}: {
  items: PermissionTreeItem[];
  selectedIds: number[];
  onChange: (ids: number[]) => void;
}) {
  return (
    <CheckboxTree
      items={items}
      selectedIds={selectedIds}
      onSelectedIdsChange={onChange}
      emptyMessage="No permissions available."
      showDescription={false}
    />
  );
}
