<?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->string('status')->default('created')->change();
        });

        if (Schema::hasColumn('compras', 'payment_status')) {
            DB::table('compras')
                ->where('payment_status', 'approved')
                ->update(['status' => 'paid']);

            DB::table('compras')
                ->where('payment_status', 'rejected')
                ->where('status', '!=', 'cancelled')
                ->update(['status' => 'rejected']);
        }

        DB::table('compras')
            ->where('status', 'pending')
            ->whereNull('payment_method')
            ->update(['status' => 'created']);

        DB::table('compras')
            ->where('status', 'pending')
            ->whereNotNull('payment_method')
            ->update(['status' => 'pending_payment']);

        if (Schema::hasColumn('compras', 'payment_status')) {
            Schema::table('compras', function (Blueprint $table) {
                $table->dropColumn('payment_status');
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        if (! Schema::hasColumn('compras', 'payment_status')) {
            Schema::table('compras', function (Blueprint $table) {
                $table->string('payment_status')->default('pending')->after('status');
            });
        }

        DB::table('compras')
            ->where('status', 'paid')
            ->update([
                'status' => 'paid',
                'payment_status' => 'approved',
            ]);

        DB::table('compras')
            ->where('status', 'rejected')
            ->update([
                'status' => 'pending',
                'payment_status' => 'rejected',
            ]);

        DB::table('compras')
            ->whereIn('status', ['created', 'pending_payment'])
            ->update([
                'status' => 'pending',
                'payment_status' => 'pending',
            ]);

        Schema::table('compras', function (Blueprint $table) {
            $table->string('status')->default('pending')->change();
        });
    }
};
