<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('compras', function (Blueprint $table) {
            $table->decimal('total', 10, 2)->default(0)->after('payment_method');
        });

        DB::table('compras')
            ->orderBy('id')
            ->chunkById(100, function ($compras): void {
                foreach ($compras as $compra) {
                    $itemsQuery = DB::table('compra_items')
                        ->where('compra_id', $compra->id);
                    $hasItems = $itemsQuery->exists();
                    $itemsTotal = $itemsQuery->sum('total');

                    $total = (float) $itemsTotal;

                    if (! $hasItems && $compra->cart_id !== null) {
                        $cartTotal = DB::table('carrito_items as carrito_item')
                            ->join('productos_variantes as variante', 'variante.id', '=', 'carrito_item.producto_variante_id')
                            ->join('productos as producto', 'producto.id', '=', 'variante.producto_id')
                            ->where('carrito_item.cart_id', $compra->cart_id)
                            ->selectRaw('COALESCE(SUM(producto.precio * carrito_item.cantidad), 0) as total')
                            ->value('total');

                        $total = (float) ($cartTotal ?? 0);
                    }

                    DB::table('compras')
                        ->where('id', $compra->id)
                        ->update([
                            'total' => number_format($total, 2, '.', ''),
                        ]);
                }
            });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('compras', function (Blueprint $table) {
            $table->dropColumn('total');
        });
    }
};
