<?php

use App\Domains\Purchase\Services\DniDistanceService;
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
    {
        Schema::table('telepagos_payment_candidates', function (Blueprint $table) {
            $table->unsignedTinyInteger('dni_distance')->nullable()->after('dni_matches');
            $table->string('payment_dni', 8)->nullable()->after('dni_distance');
            $table->string('purchase_dni', 8)->nullable()->after('payment_dni');
        });

        $dniDistance = new DniDistanceService;

        DB::table('telepagos_payment_candidates as candidate')
            ->join('telepagos_payments as payment', 'payment.id', '=', 'candidate.telepagos_payment_id')
            ->join('compras as purchase', 'purchase.id', '=', 'candidate.compra_id')
            ->select([
                'candidate.id',
                'candidate.match_reason',
                'payment.cuit_buyer',
                'purchase.transfer_payer_dni',
            ])
            ->orderBy('candidate.id')
            ->each(function (object $candidate) use ($dniDistance): void {
                if ($candidate->cuit_buyer === null || $candidate->transfer_payer_dni === null) {
                    return;
                }

                $payerDni = substr((string) $candidate->cuit_buyer, 2, -1);
                $distance = $dniDistance->distance($payerDni, (string) $candidate->transfer_payer_dni);

                if ($candidate->match_reason === 'exact_amount_different_dni' && $distance > 2) {
                    DB::table('telepagos_payment_candidates')->where('id', $candidate->id)->delete();

                    return;
                }

                DB::table('telepagos_payment_candidates')
                    ->where('id', $candidate->id)
                    ->update([
                        'dni_distance' => $distance,
                        'payment_dni' => $payerDni,
                        'purchase_dni' => $candidate->transfer_payer_dni,
                    ]);
            });
    }

    public function down(): void
    {
        Schema::table('telepagos_payment_candidates', function (Blueprint $table) {
            $table->dropColumn(['dni_distance', 'payment_dni', 'purchase_dni']);
        });
    }
};
