<?php

declare(strict_types=1);

/**
 * APO-195 Card 4 — Menu action service.
 *
 * 5 verbs: create-menu, save-placement-assignments, add-to-menu,
 * remove-menu-item, move-menu-item. Wraps MyronContentRepository methods.
 */
final class MyronMenuActionService
{
    public function __construct(
        private readonly MyronContentRepository $repository,
    ) {
    }

    /** @return array{menuId: string, name: string} */
    public function createMenu(string $name, MyronActionCallerContext $caller): array
    {
        $name = trim($name);
        if ($name === '') {
            throw new InvalidArgumentException('name is required.');
        }
        $menu = (array) $this->repository->createMenu($name);
        return ['menuId' => (string) ($menu['id'] ?? ''), 'name' => $name];
    }

    /**
     * @param array<string, mixed> $placements
     * @return array{placementsUpdated: int}
     */
    public function savePlacementAssignments(array $placements, MyronActionCallerContext $caller): array
    {
        $this->repository->updatePlacementAssignments($placements);
        return ['placementsUpdated' => count($placements)];
    }

    /** @return array{menuId: string, pageId: string} */
    public function addPageToMenu(string $menuId, string $pageId, string $label, MyronActionCallerContext $caller): array
    {
        $menuId = trim($menuId);
        $pageId = trim($pageId);
        if ($menuId === '' || $pageId === '') {
            throw new InvalidArgumentException('menuId and pageId are required.');
        }
        $this->repository->addPageToMenu($menuId, $pageId, trim($label));
        return ['menuId' => $menuId, 'pageId' => $pageId];
    }

    /** @return array{menuItemId: string, deleted: bool} */
    public function removeMenuItem(string $menuItemId, MyronActionCallerContext $caller): array
    {
        $menuItemId = trim($menuItemId);
        if ($menuItemId === '') {
            throw new InvalidArgumentException('menuItemId is required.');
        }
        $this->repository->removeMenuItem($menuItemId);
        return ['menuItemId' => $menuItemId, 'deleted' => true];
    }

    /** @return array{menuId: string, menuItemId: string} */
    public function moveMenuItem(
        string $menuId,
        string $menuItemId,
        ?string $parentMenuItemId,
        ?string $afterMenuItemId,
        MyronActionCallerContext $caller
    ): array {
        $menuId = trim($menuId);
        $menuItemId = trim($menuItemId);
        if ($menuId === '' || $menuItemId === '') {
            throw new InvalidArgumentException('menuId and menuItemId are required.');
        }
        $this->repository->moveMenuItem($menuId, $menuItemId, $parentMenuItemId, $afterMenuItemId);
        return ['menuId' => $menuId, 'menuItemId' => $menuItemId];
    }
}
