<?php

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

return new class extends Migration
{
    /**
     * Solicitudes de retiro revisadas desde admin + vínculo opcional en el ledger.
     */
    public function up(): void
    {
        Schema::create('withdrawal_requests', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('investment_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->decimal('amount', 14, 2);
            $table->string('status', 24)->default('pending');
            $table->text('admin_note')->nullable();
            $table->foreignId('processed_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('processed_at')->nullable();
            $table->timestamps();

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

        Schema::table('investment_transactions', function (Blueprint $table): void {
            $table->foreignId('withdrawal_request_id')
                ->nullable()
                ->after('applied_percent')
                ->constrained('withdrawal_requests')
                ->nullOnDelete();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('investment_transactions', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('withdrawal_request_id');
        });

        Schema::dropIfExists('withdrawal_requests');
    }
};
