<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table): void {
            $table->string('referral_code', 16)->nullable()->unique()->after('remember_token');
            $table->foreignId('referred_by_user_id')->nullable()->after('referral_code')->constrained('users')->nullOnDelete();
        });

        DB::table('users')
            ->orderBy('id')
            ->get(['id'])
            ->each(function (object $user): void {
                do {
                    $code = Str::upper(Str::random(8));
                } while (DB::table('users')->where('referral_code', $code)->exists());

                DB::table('users')->where('id', $user->id)->update(['referral_code' => $code]);
            });

        Schema::table('investment_settings', function (Blueprint $table): void {
            $table->decimal('referral_direct_percent', 8, 4)->default(7)->after('require_kyc_to_withdraw');
            $table->decimal('referral_indirect_percent', 8, 4)->default(5)->after('referral_direct_percent');
        });

        Schema::table('investment_transactions', function (Blueprint $table): void {
            $table->foreignId('beneficiary_user_id')->nullable()->after('investment_id')->constrained('users')->nullOnDelete();
            $table->unsignedTinyInteger('referral_level')->nullable()->after('withdrawal_request_id');
            $table->foreignId('referral_source_transaction_id')->nullable()->after('referral_level')->constrained('investment_transactions')->nullOnDelete();

            $table->index(['beneficiary_user_id', 'type']);
            $table->unique(['beneficiary_user_id', 'referral_level', 'referral_source_transaction_id'], 'referral_bonus_unique');
        });
    }

    public function down(): void
    {
        Schema::table('investment_transactions', function (Blueprint $table): void {
            $table->dropUnique('referral_bonus_unique');
            $table->dropIndex(['beneficiary_user_id', 'type']);
            $table->dropConstrainedForeignId('referral_source_transaction_id');
            $table->dropColumn('referral_level');
            $table->dropConstrainedForeignId('beneficiary_user_id');
        });

        Schema::table('investment_settings', function (Blueprint $table): void {
            $table->dropColumn(['referral_direct_percent', 'referral_indirect_percent']);
        });

        Schema::table('users', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('referred_by_user_id');
            $table->dropUnique(['referral_code']);
            $table->dropColumn('referral_code');
        });
    }
};
