import type { RolePermission } from '../types/role.types'

export interface PermissionGroup {
  key: string
  label: string
  permissions: RolePermission[]
}

function toGroupKey(routeName: string): string {
  return routeName
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
}

export function groupPermissionsByRoute(
  permissions: RolePermission[],
): PermissionGroup[] {
  const groups = new Map<string, RolePermission[]>()

  for (const permission of permissions) {
    const label = permission.route_name?.trim() || 'Lain-lain'
    const bucket = groups.get(label) ?? []
    bucket.push(permission)
    groups.set(label, bucket)
  }

  return Array.from(groups.entries())
    .sort(([left], [right]) => left.localeCompare(right))
    .map(([label, items]) => ({
      key: toGroupKey(label) || 'lain-lain',
      label,
      permissions: [...items].sort((left, right) =>
        left.name.localeCompare(right.name),
      ),
    }))
}

export function resolveDefaultOpenGroups(
  groups: PermissionGroup[],
  selectedPermissionIds: Set<string>,
): string[] {
  const openGroups = groups
    .filter((group) =>
      group.permissions.some((permission) =>
        selectedPermissionIds.has(permission.id),
      ),
    )
    .map((group) => group.key)

  if (openGroups.length) {
    return openGroups
  }

  return groups[0] ? [groups[0].key] : []
}
