<?php

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

return new class extends Migration {
    public function up(): void
    {
        Schema::table('applications', function (Blueprint $table) {
            $table->text('rut')->change();
            $table->text('email')->change();
            $table->text('phone')->change();
            $table->text('attachments')->nullable()->change();
            $table->string('rut_hash', 64)->nullable()->index()->after('rut');
        });

        DB::table('applications')->orderBy('id')->each(function ($application) {
            $cleanRut = strtoupper(preg_replace('/[^0-9K]/i', '', $application->rut));
            DB::table('applications')->where('id', $application->id)->update([
                'rut' => Crypt::encryptString($application->rut),
                'rut_hash' => hash_hmac('sha256', $cleanRut, config('app.key')),
                'email' => Crypt::encryptString($application->email),
                'phone' => Crypt::encryptString($application->phone),
                'data' => Crypt::encryptString($application->data),
                'attachments' => $application->attachments ? Crypt::encryptString($application->attachments) : null,
                'admin_notes' => $application->admin_notes ? Crypt::encryptString($application->admin_notes) : null,
            ]);
        });
    }

    public function down(): void
    {
        throw new RuntimeException('El cifrado de datos sensibles no se revierte automáticamente.');
    }
};
