<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('tenant_menues', function (Blueprint $table) {
            $table->dropForeign(['tenant_codigo']);
            $table->dropForeign(['menu_code']);
        });

        Schema::rename('tenant_menues', 'tenants_menues');

        Schema::table('tenants_menues', function (Blueprint $table) {
            $table->renameColumn('tenant_codigo', 'tenant_code');
            $table->json('static_content')->nullable();
        });

        Schema::table('menues', function (Blueprint $table) {
            $table->string('parent_menu_code')->nullable()->after('code');
            $table->enum('content_type', ['static', 'dynamic'])
                ->default('dynamic')
                ->after('parent_menu_code');
            $table->json('static_content_schema')->nullable()->after('content_type');
        });

        Schema::table('menues', function (Blueprint $table) {
            $table->foreign('parent_menu_code')
                ->references('code')
                ->on('menues')
                ->nullOnDelete();
        });

        Schema::table('tenants_menues', function (Blueprint $table) {
            $table->foreign('tenant_code')
                ->references('codigo')
                ->on('tenants')
                ->cascadeOnDelete();
            $table->foreign('menu_code')
                ->references('code')
                ->on('menues')
                ->cascadeOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('tenants_menues', function (Blueprint $table) {
            $table->dropForeign(['tenant_code']);
            $table->dropForeign(['menu_code']);
        });

        Schema::table('menues', function (Blueprint $table) {
            $table->dropForeign(['parent_menu_code']);
            $table->dropColumn([
                'parent_menu_code',
                'content_type',
                'static_content_schema',
            ]);
        });

        Schema::table('tenants_menues', function (Blueprint $table) {
            $table->dropColumn('static_content');
            $table->renameColumn('tenant_code', 'tenant_codigo');
        });

        Schema::rename('tenants_menues', 'tenant_menues');

        Schema::table('tenant_menues', function (Blueprint $table) {
            $table->foreign('tenant_codigo')
                ->references('codigo')
                ->on('tenants')
                ->cascadeOnDelete();
            $table->foreign('menu_code')
                ->references('code')
                ->on('menues')
                ->cascadeOnDelete();
        });
    }
};
