<?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
    {
        // 1) Create the table first
        Schema::create('submodules', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->id();                          // bigint unsigned AI
            $table->string('name', 191);           // varchar(191) not null
            $table->unsignedBigInteger('module_id'); // FK column, same type as parent
            $table->timestamps();                  // created_at / updated_at (nullable)

            // Index for the FK column (helpful and mirrors phpMyAdmin view)
            $table->index('module_id', 'submodules_module_id_index');
        });

        // 2) Then add the FK (prevents errno 150 if order is touchy)
        Schema::table('submodules', function (Blueprint $table) {
            if (Schema::hasTable('modules')) {
                $table->foreign('module_id', 'submodules_module_id_foreign')
                    ->references('id')->on('modules')
                    ->cascadeOnUpdate()
                    ->restrictOnDelete();
            }
        });
    }

    public function down(): void
    {
        // Drop FK first (if it exists), then the table
        Schema::table('submodules', function (Blueprint $table) {
            try { $table->dropForeign('submodules_module_id_foreign'); } catch (\Throwable $e) {}
        });

        Schema::dropIfExists('submodules');
    }
};

