<?php

declare(strict_types=1);

use Builder\Core\Foundation\Definition\MenuItem;
use Builder\Core\Foundation\Registry;

it('appendToMenuGroup merges children into a matching parent', function (): void {
    $registry = new Registry;

    $registry->menuItem(
        MenuItem::make('advanced')
            ->priority(95)
            ->children([MenuItem::make('health')]),
    );

    $registry->appendToMenuGroup('advanced', MenuItem::make('migrator'));

    $items = $registry->menuItems();

    expect($items)->toHaveCount(1);

    $advanced = $items[0];
    expect($advanced->getKey())->toBe('advanced')
        ->and(array_map(fn (MenuItem $c): string => $c->getKey(), $advanced->getChildren()))
        ->toBe(['health', 'migrator']);
});

it('appendToMenuGroup is silently ignored when parent never registers', function (): void {
    $registry = new Registry;

    $registry->appendToMenuGroup('ghost', MenuItem::make('lost'));

    expect($registry->menuItems())->toBe([]);
});

it('appendToMenuGroup deduplicates by child key across repeated calls', function (): void {
    $registry = new Registry;

    $registry->menuItem(MenuItem::make('advanced'));

    $registry->appendToMenuGroup('advanced', MenuItem::make('migrator'));
    $registry->appendToMenuGroup('advanced', MenuItem::make('migrator'));

    $registry->menuItems();
    $registry->menuItems();

    $advanced = $registry->menuItems()[0];

    expect($advanced->getChildren())->toHaveCount(1)
        ->and($advanced->getChildren()[0]->getKey())->toBe('migrator');
});

it('appendToMenuGroup returns self for chaining', function (): void {
    $registry = new Registry;

    $result = $registry->appendToMenuGroup('advanced', MenuItem::make('migrator'));

    expect($result)->toBe($registry);
});

it('appendToMenuGroup supports multiple parent groups independently', function (): void {
    $registry = new Registry;

    $registry->menuItem(MenuItem::make('group-a')->priority(10));
    $registry->menuItem(MenuItem::make('group-b')->priority(20));

    $registry->appendToMenuGroup('group-a', MenuItem::make('child-a'));
    $registry->appendToMenuGroup('group-b', MenuItem::make('child-b'));

    $items = $registry->menuItems();

    expect($items[0]->getChildren()[0]->getKey())->toBe('child-a')
        ->and($items[1]->getChildren()[0]->getKey())->toBe('child-b');
});
