<?php

namespace App\Http\Controllers;

use App\Models\InvestmentTransaction;
use App\Models\User;
use App\Support\InvestmentLedger;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class InvestorMovementsController extends Controller
{
    /**
     * Todos los movimientos de ledger en las inversiones del usuario autenticado.
     */
    public function index(Request $request): Response
    {
        /** @var User $user */
        $user = $request->user();

        $runningBalances = InvestmentLedger::runningBalanceAfterByLedgerTransactionId((int) $user->id);

        $mapper = fn (InvestmentTransaction $t): array => [
            'id' => $t->id,
            'type' => $t->type->value,
            'amount_usd' => number_format((float) $t->amount, 2, '.', ''),
            'balance_after_usd' => number_format(
                $runningBalances[$t->id] ?? (float) $t->balance_after,
                2,
                '.',
                '',
            ),
            'investment_txid' => $t->investment?->txid ?? '—',
            'created_at' => $t->created_at?->toIso8601String(),
            'applied_percent' => $t->applied_percent !== null
                ? number_format((float) $t->applied_percent, 4, '.', '')
                : null,
            'reference_month_index' => $t->investment_month_index,
            'withdrawal_destination_label' => $t->withdrawalRequest?->destination_label,
            'withdrawal_destination_network' => $t->withdrawalRequest?->destination_currency_network,
            'withdrawal_destination_address' => $t->withdrawalRequest?->destination_address,
            'withdrawal_payout_txid' => $t->withdrawalRequest?->payout_txid,
        ];

        $paginator = InvestmentTransaction::query()
            ->visibleInUserLedger($user->id)
            ->with([
                'investment:id,user_id,txid',
                'withdrawalRequest:id,payout_txid,destination_currency_network,destination_address,destination_label',
            ])
            ->orderByDesc('id')
            ->paginate(15)
            ->withQueryString();

        $paginator->through($mapper);

        return Inertia::render('balances/movements', [
            'transactions' => $paginator,
        ]);
    }
}
