<?php

use App\Domains\Authorization\Enums\RoleCode;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        $now = now();

        DB::table('roles')->insertOrIgnore([
            [
                'codigo' => RoleCode::Admin->value,
                'nombre' => 'Administrador general',
                'descripcion' => 'Administra la plataforma y todos sus tenants.',
                'created_at' => $now,
                'updated_at' => $now,
            ],
            [
                'codigo' => RoleCode::User->value,
                'nombre' => 'Usuario',
                'descripcion' => 'Cliente final limitado a sus propios datos y operaciones.',
                'created_at' => $now,
                'updated_at' => $now,
            ],
        ]);

        Schema::table('users', function (Blueprint $table): void {
            $table->string('rol_codigo')->default(RoleCode::User->value)->after('id');
            $table->string('tenant_codigo')->nullable()->after('rol_codigo');

            $table->foreign('rol_codigo')
                ->references('codigo')
                ->on('roles')
                ->cascadeOnUpdate()
                ->restrictOnDelete();
            $table->foreign('tenant_codigo')
                ->references('codigo')
                ->on('tenants')
                ->cascadeOnUpdate()
                ->restrictOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table): void {
            $table->dropForeign(['tenant_codigo']);
            $table->dropForeign(['rol_codigo']);
            $table->dropColumn(['tenant_codigo', 'rol_codigo']);
        });
    }
};
