<?php

namespace Daylight\Core\Modules\MenuBuilder\Registries;

use Daylight\Core\Modules\MenuBuilder\Menu;
use Daylight\Core\Modules\MenuBuilder\Menu as MenuEntity;
use Daylight\Core\Modules\MenuBuilder\Settings\Menus;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;

class MenuRegistry
{
    protected Collection $menus;

    public function __construct()
    {
        $this->menus = collect();
    }

    public function register(Menu $menu): self
    {
        $this->menus->put($menu->getKey(), $menu);

        return $this;
    }

    public static function addMenu(Menu $menu): self
    {
        return app(MenuRegistry::class)->register($menu);
    }

    public function all(): Collection
    {
        return $this->menus;
    }

    public static function getMenuItems(MenuEntity $menu)
    {
        return Cache::rememberForever($menu->getKey() . '_' . app()->getLocale(), function () use ($menu) {
            $menuId = app(Menus::class)->menus[$menu->getKey()] ?? null;

            if (! $menuId) {
                return collect();
            }

            $menu = \Daylight\Core\Modules\MenuBuilder\Models\Menu::query()
                ->whereId($menuId)
                ->with([
                    'translations' => function ($builder) {
                        $builder
                            ->whereLocale(app()->getLocale())
                            ->with([
                                'items' => fn ($q) => $q->whereParentId(null)->with('children.children'),
                            ]);
                    },
                ])
                ->first();

            return $menu->translations?->first()->items;
        });
    }
}
