<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Cache;

class Menu extends Model
{
    protected $fillable = ['name', 'location'];

    public function items(): HasMany
    {
        return $this->hasMany(MenuItem::class)->orderBy('sort');
    }

    public static function location(string $location): array
    {
        return Cache::rememberForever("menu.{$location}", function () use ($location) {
            $menu = static::where('location', $location)->with('items.page')->first();

            return $menu?->items->map(fn (MenuItem $item) => [
                'label'   => $item->label,
                'url'     => $item->resolvedUrl(),
                'new_tab' => $item->new_tab,
            ])->all() ?? [];
        });
    }

    public static function flush(): void
    {
        foreach (static::pluck('location') as $location) {
            Cache::forget("menu.{$location}");
        }
    }

    protected static function booted(): void
    {
        static::saved(fn () => static::flush());
        static::deleted(fn () => static::flush());
    }
}
