<?php

declare(strict_types=1);

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

/**
 * Superadmin › Tabellen (kolomdefaults en gebruikers-tabelstate reset).
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('navigation_nodes')) {
            return;
        }

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

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

        NavigationNode::query()
            ->where('parent_id', $superadmin->id)
            ->where('sort_order', '>=', 3)
            ->increment('sort_order');

        NavigationNode::query()->create([
            'parent_id' => $superadmin->id,
            'module_id' => null,
            'sort_order' => 3,
            'key' => 'superadmin-datatable-settings',
            'label' => 'Tabellen',
            'icon' => 'pi pi-fw pi-table',
            'route' => '/superadmin/datatable-settings',
            'permission' => 'platform.superadmin',
            'is_header' => false,
            'pinned_bottom' => false,
            'description' => 'Standaardkolommen per tabel en gebruikersweergave terugzetten',
        ]);
    }

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

        $removed = NavigationNode::query()->where('key', 'superadmin-datatable-settings')->delete();
        if ($removed === 0) {
            return;
        }

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

        NavigationNode::query()
            ->where('parent_id', $superadmin->id)
            ->where('sort_order', '>', 3)
            ->decrement('sort_order');
    }
};
