<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
use Maestro\Core\Database\Seeders\ModuleAndNavigationSeeder;
use Maestro\Core\Models\NavigationNode;

/**
 * Inserts the Superadmin "Installation health" nav item for existing databases without
 * re-running {@see ModuleAndNavigationSeeder} (which purges navigation).
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('navigation_nodes')) {
            return;
        }

        if (NavigationNode::query()->where('key', 'superadmin-installation-health')->exists()) {
            return;
        }

        $superadmin = NavigationNode::query()->where('key', 'superadmin')->first();
        if ($superadmin === null) {
            return;
        }

        $children = NavigationNode::query()
            ->where('parent_id', $superadmin->id)
            ->orderByDesc('sort_order')
            ->get();

        foreach ($children as $child) {
            $child->update(['sort_order' => $child->sort_order + 1]);
        }

        NavigationNode::query()->create([
            'parent_id' => $superadmin->id,
            'module_id' => null,
            'sort_order' => 0,
            'key' => 'superadmin-installation-health',
            'label' => 'Installation health',
            'icon' => 'pi pi-fw pi-chart-bar',
            'route' => '/superadmin/setup',
            'permission' => 'platform.superadmin',
            'is_header' => false,
            'pinned_bottom' => false,
            'description' => 'Readiness checklist (migrations, seed, toggles)',
        ]);
    }

    public function down(): void
    {
        if (! Schema::hasTable('navigation_nodes')) {
            return;
        }

        NavigationNode::query()->where('key', 'superadmin-installation-health')->delete();
    }
};
