<?php

namespace App\Http\Controllers;

use App\Enums\WithdrawalRequestStatus;
use App\Models\InvestmentSetting;
use App\Models\User;
use App\Models\UserWallet;
use App\Models\WithdrawalRequest;
use App\Support\UserInvestmentPortfolio;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class InvestorBalancesController extends Controller
{
    /**
     * Resumen financiero para el inversionista: capital, inversiones y retiros solicitados.
     */
    public function index(Request $request): Response
    {
        /** @var User $user */
        $user = $request->user();

        $portfolio = UserInvestmentPortfolio::detailPage($user);

        $feeSettings = InvestmentSetting::current();

        $walletCount = $user->wallets()->count();

        $portfolioWithdrawalPending = WithdrawalRequest::query()
            ->where('user_id', $user->id)
            ->whereIn('status', [WithdrawalRequestStatus::Pending, WithdrawalRequestStatus::PendingEmail])
            ->exists();

        $wallets = $user->wallets()->get()->map(fn (UserWallet $w): array => [
            'id' => $w->id,
            'currency_network' => $w->currency_network,
            'address' => $w->address,
            'label' => $w->label,
            'is_default' => $w->is_default,
        ])->values()->all();

        $pendingWithdrawals = WithdrawalRequest::query()
            ->where('user_id', $user->id)
            ->whereIn('status', [WithdrawalRequestStatus::Pending, WithdrawalRequestStatus::PendingEmail])
            ->with(['investment:id,txid'])
            ->orderByDesc('created_at')
            ->get()
            ->map(fn (WithdrawalRequest $wr): array => self::withdrawalLite($wr));

        $recentWithdrawals = WithdrawalRequest::query()
            ->where('user_id', $user->id)
            ->whereIn('status', [WithdrawalRequestStatus::Approved, WithdrawalRequestStatus::Rejected])
            ->with(['investment:id,txid'])
            ->orderByDesc('processed_at')
            ->limit(12)
            ->get()
            ->map(fn (WithdrawalRequest $wr): array => self::withdrawalLite($wr));

        return Inertia::render(
            'balances/index',
            array_merge($portfolio, [
                'wallet_count' => $walletCount,
                'portfolio_withdrawal_pending' => $portfolioWithdrawalPending,
                'wallets' => $wallets,
                'withdrawals_pending' => $pendingWithdrawals,
                'withdrawals_recent' => $recentWithdrawals,
                'withdrawal_fee_percent' => number_format((float) $feeSettings->withdrawal_fee_percent, 4, '.', ''),
                'withdrawal_fee_fixed' => number_format((float) $feeSettings->withdrawal_fee_fixed, 2, '.', ''),
                'min_withdrawal_amount' => number_format((float) $feeSettings->min_withdrawal_amount, 2, '.', ''),
            ]),
        );
    }

    /**
     * @return array<string, mixed>
     */
    private static function withdrawalLite(WithdrawalRequest $wr): array
    {
        return [
            'id' => $wr->id,
            'amount_usd' => number_format((float) $wr->amount, 2, '.', ''),
            'fee_total_usd' => number_format((float) $wr->fee_total, 2, '.', ''),
            'net_amount_usd' => $wr->net_amount !== null
                ? number_format((float) $wr->net_amount, 2, '.', '')
                : number_format(max(0, (float) $wr->amount - (float) $wr->fee_total), 2, '.', ''),
            'status' => $wr->status->value,
            'investment_txid' => $wr->investment_id === null
                ? 'Balance consolidado'
                : ($wr->investment?->txid ?? '—'),
            'destination_network' => $wr->destination_currency_network,
            'destination_address' => $wr->destination_address,
            'destination_label' => $wr->destination_label,
            'payout_txid' => $wr->payout_txid,
            'created_at' => $wr->created_at?->toIso8601String(),
            'processed_at' => $wr->processed_at?->toIso8601String(),
        ];
    }
}
