<?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
    {
        Schema::create('transactions', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->uuid('user_id')->constrained()->cascadeOnDelete();
            $table->uuid('wallet_id')->constrained()->cascadeOnDelete();
            $table->uuid('bill_service_id')->nullable()->constrained()->nullOnDelete();
            $table->uuid('bill_variation_id')->nullable()->constrained()->nullOnDelete();
            $table->string('reference')->unique();
            $table->string('provider_reference')->nullable();
            $table->string('receipt_number')->nullable()->unique();
            $table->enum('type', ['airtime', 'data', 'cable', 'electricity', 'exam_pin', 'other'])->index();
            $table->string('service_name');
            $table->string('provider')->default('vtpass');
            $table->string('network')->nullable();
            $table->string('customer_number');
            $table->string('customer_name')->nullable();
            $table->string('customer_email')->nullable();
            $table->decimal('amount', 15, 2);
            $table->decimal('fee', 15, 2)->default(0.00);
            $table->decimal('total_amount', 15, 2);
            $table->decimal('cashback', 15, 2)->default(0.00);
            $table->decimal('wallet_balance_before', 15, 2);
            $table->decimal('wallet_balance_after', 15, 2);
            $table->enum('status', [
                'pending', 'processing', 'successful', 'failed',
                'refunded', 'reversed', 'timeout', 'cancelled'
            ])->default('pending');
            $table->json('provider_response')->nullable();
            $table->json('provider_request')->nullable();
            $table->json('token_data')->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->string('device')->nullable();
            $table->text('description')->nullable();
            $table->text('failure_reason')->nullable();
            $table->string('idempotency_key')->nullable()->unique();
            $table->timestamp('processed_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->index('status');
            $table->index('created_at');
            $table->index('customer_number');
            $table->index(['user_id', 'status']);
            $table->index(['user_id', 'type']);
            $table->index(['user_id', 'created_at']);
        });
    }

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