<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        DB::table('leads')
            ->where('credited_points', '>', 0)
            ->orderBy('id')
            ->chunkById(500, function ($leads): void {
                $rows = $leads->map(fn ($lead): array => [
                    'lead_id' => $lead->id,
                    'admin_id' => null,
                    'token' => 'legacy-backfill:'.$lead->id,
                    'action' => 'legacy_credit',
                    'points' => $lead->credited_points,
                    'credited_before' => 0,
                    'credited_after' => $lead->credited_points,
                    'requested_unit' => 'coins',
                    'requested_amount' => $lead->credited_points,
                    'note' => 'Opening credited balance migrated from the lead record.',
                    'created_at' => $lead->created_at,
                    'updated_at' => $lead->updated_at,
                ])->all();

                DB::table('lead_adjustments')->insertOrIgnore($rows);
            });
    }

    public function down(): void
    {
        DB::table('lead_adjustments')->where('token', 'like', 'legacy-backfill:%')->delete();
    }
};
