<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('maestro_modules') || ! Schema::hasTable('maestro_navigation_nodes')) {
            return;
        }

        $offersId = DB::table('maestro_modules')->where('slug', 'offers')->value('id');
        if (is_numeric($offersId)) {
            DB::table('maestro_navigation_nodes')
                ->whereIn('key', ['settings-offers-catalog', 'settings-offers-templates'])
                ->update(['module_id' => (int) $offersId]);
        }

        $invoicesId = DB::table('maestro_modules')->where('slug', 'invoices')->value('id');
        if (is_numeric($invoicesId)) {
            DB::table('maestro_navigation_nodes')
                ->where('key', 'settings-invoices-vat')
                ->update(['module_id' => (int) $invoicesId]);
        }
    }

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

        DB::table('maestro_navigation_nodes')
            ->whereIn('key', [
                'settings-offers-catalog',
                'settings-offers-templates',
                'settings-invoices-vat',
            ])
            ->update(['module_id' => null]);
    }
};
