<?php

namespace Daylight\Core\Modules\MenuBuilder\Listeners;

use Daylight\Core\Modules\MenuBuilder\Events\MenuUpdated;
use Daylight\Core\Modules\MenuBuilder\Settings\Menus;
use Daylight\Core\Modules\Multilingualism\Multilingualism;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;

class ClearNavigationCache
{
    public function __construct(public Menus $navigationSettings)
    {
        //
    }

    public function handle(MenuUpdated $event): void
    {
        $this->getCacheKeys($event->menu->id)->each(function (string $key) {
            Cache::forget($key);
        });
    }

    private function getCacheKeys(int $menuId): Collection
    {
        $menus = $this->navigationSettings->menus;

        if (! in_array($menuId, $menus)) {
            return collect();
        }

        $key = array_search($menuId, $menus);

        return Multilingualism::getAvailableLocales()->map(function ($locale) use ($key) {
            return $key . '_' . $locale;
        });
    }
}
