<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('wallet_transactions')) {
            return;
        }
        
        Schema::create('wallet_transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('wallet_id')->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            // Include all possible enum values from the start
            $table->enum('type', ['deposit', 'withdrawal', 'commission', 'purchase', 'refund', 'bonus', 'transfer', 'fee', 'subscription', 'withdrawal_request', 'pool_share', 'seller_sale', 'seller_commission']);
            $table->decimal('amount', 15, 2);
            $table->decimal('balance_before', 15, 2);
            $table->decimal('balance_after', 15, 2);
            $table->string('currency', 3)->default('XOF');
            $table->enum('status', ['pending', 'completed', 'failed', 'cancelled'])->default('pending');
            $table->string('reference')->unique();
            $table->text('description')->nullable();
            $table->json('metadata')->nullable();
            $table->foreignId('related_order_id')->nullable()->constrained('orders')->onDelete('set null');
            $table->foreignId('related_commission_id')->nullable()->constrained('commissions')->onDelete('set null');
            $table->unsignedBigInteger('withdrawal_id')->nullable(); // AJOUTÉ
            $table->timestamps();
            
            $table->index(['wallet_id', 'type']);
            $table->index(['user_id', 'created_at']);
            $table->index('withdrawal_id'); // AJOUTÉ
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('wallet_transactions');
    }
};
