<?php

declare(strict_types=1);

namespace apexl\Io\modules\tabulator\Services;

use Arrayy\Type\ArrayCollection;

final readonly class TabulatorTreeBuilderService
{
    public function buildTree(array $rows, string $idKey = 'id', string $parentKey = 'parent_id'): ArrayCollection
    {
        $tree = [];
        $indexed = [];

        foreach ($rows as &$row) {
            $indexed[$row[$idKey]] = &$row;
        }

        foreach ($rows as &$row) {
            $parentId = $row[$parentKey];
            if ($parentId !== null && isset($indexed[$parentId])) {
                if (!isset($indexed[$parentId]['children'])) {
                    $indexed[$parentId]['children'] = [];
                }
                $indexed[$parentId]['children'][] = &$row;
            } else {
                $tree[] = &$row;
            }
        }

        return ArrayCollection::createFromArray($tree);
    }

}