<?php

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

/**
 * Authored navigation. Previously the navbar was derived from enabled sections,
 * so a client could not add a dropdown, an external link, or reorder items.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('website_menus')) {
            Schema::create('website_menus', function (Blueprint $table) {
                $table->id();
                $table->foreignId('academy_id')->constrained('academies');
                $table->uuid('uuid')->unique();
                $table->string('key', 40);
                $table->string('name', 120)->nullable();
                $table->timestamps();

                $table->unique(['academy_id', 'key']);
            });

            DB::statement("ALTER TABLE website_menus ADD CONSTRAINT website_menus_key_check
                CHECK (key IN ('primary', 'footer', 'footer_secondary', 'mobile', 'utility'))");
        }

        if (! Schema::hasTable('website_menu_items')) {
            Schema::create('website_menu_items', function (Blueprint $table) {
                $table->id();
                $table->foreignId('academy_id')->constrained('academies');
                $table->foreignId('website_menu_id')->constrained('website_menus')->cascadeOnDelete();
                $table->foreignId('parent_id')->nullable()
                    ->constrained('website_menu_items')->cascadeOnDelete();

                $table->string('label')->nullable();
                $table->string('label_en')->nullable();

                $table->string('link_type', 20)->default('page');
                $table->foreignId('website_page_id')->nullable()
                    ->constrained('website_pages')->nullOnDelete();
                $table->string('url', 500)->nullable();
                $table->string('anchor', 120)->nullable();
                $table->string('route_name', 120)->nullable();

                $table->string('icon', 60)->nullable();
                $table->boolean('open_in_new_tab')->default(false);
                $table->boolean('is_visible')->default(true);
                $table->boolean('highlight')->default(false);
                $table->unsignedSmallInteger('sort_order')->default(0);

                $table->timestamps();

                $table->index(['academy_id', 'website_menu_id', 'sort_order']);
                $table->index(['academy_id', 'parent_id', 'sort_order']);
            });

            DB::statement("ALTER TABLE website_menu_items ADD CONSTRAINT website_menu_items_link_type_check
                CHECK (link_type IN ('page', 'url', 'anchor', 'route', 'none'))");
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('website_menu_items');
        Schema::dropIfExists('website_menus');
    }
};
