<?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('referrals', function (Blueprint $table) {
            $table->id();
            $table->foreignId('referrer_user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('referred_user_id')->constrained('users')->cascadeOnDelete();
            $table->string('referral_code', 32);
            $table->enum('status', ['pending', 'rewarded', 'cancelled'])->default('pending');
            $table->decimal('reward_amount', 14, 2)->nullable();
            $table->string('wallet_ledger_reference', 191)->nullable();
            $table->timestamp('rewarded_at')->nullable();
            $table->timestamp('cancelled_at')->nullable();
            $table->json('meta_json')->nullable();
            $table->timestamps();

            $table->unique('referred_user_id');
            $table->unique('wallet_ledger_reference');
            $table->index(['referrer_user_id', 'status']);
            $table->index(['status', 'created_at']);
            $table->index('referral_code');
        });
    }

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