<?php

namespace App\Observers;

use App\Models\Language;
use App\Models\Menu;
use Illuminate\Support\Facades\Cache;

class MenuObserver
{
    public function saved(Menu $menu): void
    {
        $this->flush($menu);
    }

    public function deleted(Menu $menu): void
    {
        $this->flush($menu);
    }

    public function flush(Menu $menu): void
    {
        $brandKey = $menu->brand_id ?? 'master';
        $locales = Language::where('status', true)->pluck('a2_iso')->all();
        if (empty($locales)) {
            $locales = [config('app.locale'), config('app.fallback_locale')];
        }
        foreach (array_unique($locales) as $locale) {
            Cache::forget("menu_tree:{$menu->slug}:{$locale}:{$brandKey}");
        }
    }
}
