<?php

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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('logseguridades', function (Blueprint $table) {
            $table->string('accion_descripcion')->nullable()->after('accion_id');
            $table->string('responsable_nombre')->nullable()->after('persona_id');
        });

        DB::statement(<<<'SQL'
            UPDATE logseguridades AS logs
            LEFT JOIN accioneslogs AS acciones ON acciones.id = logs.accion_id
            LEFT JOIN personas AS personas ON personas.id = logs.persona_id
            SET
                logs.accion_descripcion = COALESCE(logs.accion_descripcion, acciones.descripcion),
                logs.responsable_nombre = COALESCE(
                    logs.responsable_nombre,
                    NULLIF(TRIM(CONCAT(COALESCE(personas.nombre, ''), ' ', COALESCE(personas.apellido, ''))), '')
                )
        SQL);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('logseguridades', function (Blueprint $table) {
            $table->dropColumn(['accion_descripcion', 'responsable_nombre']);
        });
    }
};
