<?php

use App\Models\Usuario;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        DB::table('users')
            ->select(['id', 'cargo', 'tipo'])
            ->orderBy('id')
            ->chunkById(100, function ($users): void {
                foreach ($users as $user) {
                    $roleKey = Usuario::resolveRoleKey(
                        isset($user->cargo) ? (string) $user->cargo : null,
                        $user->tipo ?? null,
                    );

                    if ($roleKey === null) {
                        continue;
                    }

                    DB::table('users')
                        ->where('id', $user->id)
                        ->update([
                            'cargo' => Usuario::roleLabelFromKey($roleKey),
                            'tipo' => Usuario::roleTypeFromKey($roleKey),
                        ]);
                }
            });

        DB::table('cargos')->whereNotIn('nombre', array_values(Usuario::ROLE_LABELS))->delete();

        foreach (Usuario::cargoOptions() as $cargo) {
            DB::table('cargos')->updateOrInsert(
                ['nombre' => $cargo],
                ['created_at' => now(), 'updated_at' => now()]
            );
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Normalizacion irreversible: no se restauran los valores anteriores.
    }
};