<?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
{
    public function up(): void
    {
        DB::table('compras')
            ->whereNotNull('stock_reservation_id')
            ->orderBy('id')
            ->chunkById(500, function ($purchases): void {
                foreach ($purchases as $purchase) {
                    DB::table('stock_reservations')
                        ->where('id', $purchase->stock_reservation_id)
                        ->where('status', 'active')
                        ->update(['expires_at' => $purchase->expires_at]);
                }
            });

        Schema::table('compras', function (Blueprint $table): void {
            $table->dropIndex(['expires_at']);
            $table->dropColumn('expires_at');
        });
    }

    public function down(): void
    {
        Schema::table('compras', function (Blueprint $table): void {
            $table->timestamp('expires_at')->nullable()->index()->after('payment_method');
        });

        DB::table('compras')
            ->whereNotNull('stock_reservation_id')
            ->orderBy('id')
            ->chunkById(500, function ($purchases): void {
                foreach ($purchases as $purchase) {
                    DB::table('compras')
                        ->where('id', $purchase->id)
                        ->update([
                            'expires_at' => DB::table('stock_reservations')
                                ->where('id', $purchase->stock_reservation_id)
                                ->value('expires_at'),
                        ]);
                }
            });
    }
};
