<?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
    {
        Schema::table('compras', function (Blueprint $table): void {
            $table->timestamp('expires_at')->nullable()->index()->after('payment_method');
        });

        DB::table('compras')
            ->whereIn('status', ['created', 'pending_payment'])
            ->whereNull('expires_at')
            ->update([
                'expires_at' => now()->addMinutes(
                    max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
                ),
            ]);
    }

    public function down(): void
    {
        Schema::table('compras', function (Blueprint $table): void {
            $table->dropColumn('expires_at');
        });
    }
};
