<?php

declare(strict_types=1);

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

/**
 * Removes the legacy "Workspace" section header; top-level app links are ungrouped.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('navigation_nodes')) {
            return;
        }

        NavigationNode::query()->where('key', 'nav-section-workspace')->delete();
    }

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

        if (NavigationNode::query()->where('key', 'nav-section-workspace')->exists()) {
            return;
        }

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

        $siblings = NavigationNode::query()
            ->where('parent_id', $root->id)
            ->orderBy('sort_order')
            ->get();

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

        NavigationNode::query()->create([
            'parent_id' => $root->id,
            'module_id' => null,
            'sort_order' => 0,
            'key' => 'nav-section-workspace',
            'label' => 'Workspace',
            'icon' => null,
            'route' => null,
            'permission' => null,
            'is_header' => true,
            'pinned_bottom' => false,
            'description' => null,
        ]);
    }
};
