<?php

namespace Apexl\Io\User\Display\Components;

use Apexl\Io\Component\Collections\ComponentCollection;
use Apexl\Io\Component\Collections\ComponentPropertyCollection;
use Apexl\Io\Component\Factories\ComponentPropertyFactory;
use Apexl\Io\Display\Components\DropdownMenu;
use Apexl\Io\Exceptions\RouteNotFoundException;
use Apexl\Io\Menu\MenuItem;
use Apexl\Io\Services\RouteUrls;
use Apexl\Io\User\Interfaces\MasqueradeServiceInterface;
use Apexl\Io\User\Services\CurrentUserFactory;
use Arrayy\Type\StringCollection;

final readonly class AccountMenuDropdown extends DropdownMenu
{
    public function __construct(
        private MasqueradeServiceInterface $masqueradeService,
        private RouteUrls $routeUrls,
        ComponentPropertyFactory $propertyFactory,
        ComponentPropertyCollection $props,
        ComponentCollection $components,
        StringCollection $classes,
        CurrentUserFactory $currentUserFactory
    ) {
        parent::__construct($propertyFactory, $props, $components, $classes, $currentUserFactory);
    }

    /**
     * @throws RouteNotFoundException
     */
    public function init(): void
    {
        $currentUser = $this->currentUserFactory->get();

        $this->addMenuItems([
            $this->logoutOrEndMasqueradeItem()
        ])
            ->addIcon("user-circle")
            ->addClass('col top-bar-user-menu')
            ->setTitle(
                title: $currentUser->getNiceName(),
            );
    }

    /**
     * @throws RouteNotFoundException
     */
    private function logoutOrEndMasqueradeItem(): MenuItem
    {
        return $this->masqueradeService->isMasquerading() ? new MenuItem(
            [
                'routeName' => 'user.masquerade.end',
                'title' => 'End Masquerade',
                'icon' => 'arrow-right-from-bracket',
                'weight' => 999,
            ],
            $this->routeUrls->url('user.masquerade.end')
        ) : new MenuItem(
            [
                'routeName' => 'user.logout',
                'title' => 'Logout',
                'icon' => 'arrow-right-from-bracket',
                'weight' => 999,
            ],
            $this->routeUrls->url('user.logout'),
        );
    }
}
