<?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('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('referred_user_id')->constrained('users')->cascadeOnDelete();
            $table->integer('level')->default(1); // 1, 2, 3
            $table->decimal('commission_percent', 5, 2)->default(0);
            $table->decimal('total_earnings', 20, 8)->default(0);
            $table->decimal('withdrawable', 20, 8)->default(0);
            $table->timestamps();
            $table->unique(['user_id', 'referred_user_id']);
            $table->index(['user_id', 'level']);
        });
    }

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