<?php

namespace App\Http\Controllers\Admin;

use App\Enums\InvestmentTransactionType;
use App\Http\Controllers\Controller;
use App\Models\InvestmentTransaction;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Collection;

class WithdrawalHistoryController extends Controller
{
    /**
     * @return Collection<int, array<string, mixed>>
     */
    public static function ledgerRows(int $limit = 500): Collection
    {
        return InvestmentTransaction::query()
            ->where('type', InvestmentTransactionType::Withdrawal)
            ->with([
                'investment:id,user_id,txid,amount,capital_balance',
                'investment.user:id,first_name,last_name,email',
                'withdrawalRequest:id,status,user_id',
            ])
            ->orderByDesc('id')
            ->limit($limit)
            ->get()
            ->map(function (InvestmentTransaction $t): array {
                $user = $t->investment?->user;
                $investorName = trim(($user?->first_name ?? '').' '.($user?->last_name ?? ''));

                return [
                    'id' => $t->id,
                    'created_at' => $t->created_at?->toIso8601String(),
                    'amount_usd' => number_format((float) $t->amount, 2, '.', ''),
                    'balance_after_usd' => number_format((float) $t->balance_after, 2, '.', ''),
                    'txid' => $t->investment?->txid ?? '—',
                    'investor_email' => $t->investment?->user?->email,
                    'investor_name' => $investorName !== '' ? $investorName : '—',
                    'via_request_id' => $t->withdrawal_request_id,
                    'via_request_status' => $t->withdrawalRequest?->status->value ?? null,
                ];
            });
    }

    public function index(): RedirectResponse
    {
        return redirect()->route('admin.withdrawals.requests.index', ['tab' => 'historial']);
    }
}
