<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Rename modules table to portals
        Schema::rename('modules', 'portals');
        
        // Rename pivot table
        Schema::rename('module_user', 'portal_user');
        
        // Update foreign key names and enum values in portal_user table
        Schema::table('portal_user', function (Blueprint $table) {
            $table->renameColumn('module_id', 'portal_id');
        });
        
        // Update ENUM values from module_admin to portal_admin
        DB::statement("ALTER TABLE portal_user MODIFY COLUMN role_scope ENUM('portal_admin', 'user') DEFAULT 'user' COMMENT 'Role scope within this portal: portal_admin can access admin side, user can access user side only'");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Reverse ENUM values
        DB::statement("ALTER TABLE portal_user MODIFY COLUMN role_scope ENUM('module_admin', 'user') DEFAULT 'user' COMMENT 'Role scope within this module: module_admin can access admin side, user can access user side only'");
        
        // Reverse portal_user table changes
        Schema::table('portal_user', function (Blueprint $table) {
            $table->renameColumn('portal_id', 'module_id');
        });
        
        // Rename back to original names
        Schema::rename('portal_user', 'module_user');
        Schema::rename('portals', 'modules');
    }
};
