<?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::create('permisos', function (Blueprint $table): void {
            $table->id();
            $table->string('codigo')->unique();
            $table->string('nombre');
            $table->text('descripcion')->nullable();
            $table->timestamps();
        });

        Schema::create('roles', function (Blueprint $table): void {
            $table->id();
            $table->string('codigo')->unique();
            $table->string('nombre');
            $table->text('descripcion')->nullable();
            $table->timestamps();
        });

        Schema::create('roles_permisos', function (Blueprint $table): void {
            $table->id();
            $table->string('codigo_permiso');
            $table->string('rol_codigo');
            $table->timestamps();

            $table->foreign('codigo_permiso')
                ->references('codigo')
                ->on('permisos')
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->foreign('rol_codigo')
                ->references('codigo')
                ->on('roles')
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->unique(['rol_codigo', 'codigo_permiso']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('roles_permisos');
        Schema::dropIfExists('roles');
        Schema::dropIfExists('permisos');
    }
};
