<?php

use App\Models\Group;
use App\Models\Menu;
use App\Models\MenuType;
use App\Services\NavigationService;
use Illuminate\Database\Migrations\Migration;

return new class extends Migration
{
    /**
     * Tambah menu "Pengaturan Sistem" (admin/developer) ke live DB.
     */
    public function up(): void
    {
        $sideType = MenuType::where('type', 'Side menu')->first();
        if (! $sideType) {
            return;
        }

        $menu = Menu::firstOrCreate(
            ['route' => 'admin-settings.edit', 'label' => 'Pengaturan'],
            [
                'section' => 'Sistem',
                'route' => 'admin-settings.edit',
                'link' => null,
                'icon' => 'settings',
                'menu_type_id' => $sideType->id,
                'parent_id' => null,
                'sort_order' => 100,
                'status' => true,
            ]
        );

        $groupIds = Group::whereIn('name', [Group::ADMIN, Group::DEVELOPER])->pluck('id')->all();
        $menu->groups()->syncWithoutDetaching($groupIds);

        // Invalidate cache nav agar menu langsung muncul.
        app(NavigationService::class)->clearCache();
    }

    public function down(): void
    {
        $menu = Menu::where('route', 'admin-settings.edit')->first();
        if ($menu) {
            $menu->groups()->detach();
            $menu->delete();
            app(NavigationService::class)->clearCache();
        }
    }
};
