<?php

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

class AddIdToRoleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Primero creamos una tabla temporal
        Schema::create('role_user_temp', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('role_id');
            $table->unsignedBigInteger('user_id');
            $table->string('user_type');
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('updated_at')->nullable();
            
            $table->unique(['user_id', 'role_id', 'user_type']);
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade')->onUpdate('cascade');
        });

        // Copiamos los datos
        DB::statement('INSERT INTO role_user_temp (role_id, user_id, user_type, created_at, updated_at) SELECT role_id, user_id, user_type, created_at, updated_at FROM role_user');

        // Eliminamos la tabla original
        Schema::drop('role_user');

        // Renombramos la tabla temporal
        Schema::rename('role_user_temp', 'role_user');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Creamos una tabla temporal con la estructura antigua
        Schema::create('role_user_temp', function (Blueprint $table) {
            $table->unsignedBigInteger('role_id');
            $table->unsignedBigInteger('user_id');
            $table->string('user_type');
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('updated_at')->nullable();
            
            $table->primary(['user_id', 'role_id', 'user_type']);
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade')->onUpdate('cascade');
        });

        // Copiamos los datos (excluyendo el id)
        DB::statement('INSERT INTO role_user_temp (role_id, user_id, user_type, created_at, updated_at) SELECT role_id, user_id, user_type, created_at, updated_at FROM role_user');

        // Eliminamos la tabla actual
        Schema::drop('role_user');

        // Renombramos la tabla temporal
        Schema::rename('role_user_temp', 'role_user');
    }
} 