<?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('carritos', function (Blueprint $table): void {
            $table->foreignId('current_purchase_id')
                ->nullable()
                ->after('origin')
                ->constrained('compras')
                ->nullOnDelete();
            $table->unique('current_purchase_id', 'carts_current_purchase_unique');
        });

        DB::table('carritos')
            ->select('id')
            ->orderBy('id')
            ->each(function (object $cart): void {
                $purchaseId = DB::table('compras')
                    ->where('cart_id', $cart->id)
                    ->whereIn('status', ['created', 'pending_payment'])
                    ->latest('id')
                    ->value('id');

                if ($purchaseId !== null) {
                    DB::table('carritos')
                        ->where('id', $cart->id)
                        ->update(['current_purchase_id' => $purchaseId]);
                }
            });
    }

    public function down(): void
    {
        Schema::table('carritos', function (Blueprint $table): void {
            $table->dropUnique('carts_current_purchase_unique');
            $table->dropConstrainedForeignId('current_purchase_id');
        });
    }
};
