<?php

namespace App\Http\Controllers;

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

class InvestmentTransactionsController extends Controller
{
    /**
     * Movimientos de una inversión (solo el titular): depósitos, acreditaciones, retiros.
     */
    public function index(Request $request, Investment $investment): Response
    {
        abort_unless((int) $investment->user_id === (int) $request->user()->id, 403);
        abort_if(InvestmentLedger::isAdminAdjustmentInvestment($investment), 404);

        $current = (float) ($investment->capital_balance ?? $investment->amount);

        $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((float) $t->balance_after, 2, '.', ''),
            'applied_percent' => $t->applied_percent !== null
                ? number_format((float) $t->applied_percent, 4, '.', '')
                : null,
            'reference_month' => $t->platformMonthAccrual?->reference_month,
            'investment_month_index' => $t->investment_month_index,
            'accrual_on' => $t->accrual_on?->toDateString(),
            'gain_period_start' => $t->gain_period_start?->toDateString(),
            'gain_period_end' => $t->gain_period_end?->toDateString(),
            'created_at' => $t->created_at?->toIso8601String(),
        ];

        $paginator = $investment->transactions()
            ->whereNull('beneficiary_user_id')
            ->with(['platformMonthAccrual:id,reference_month'])
            ->orderByDesc('id')
            ->paginate(15)
            ->withQueryString();

        $paginator->through($mapper);

        return Inertia::render('investments/investment-transactions', [
            'investment' => [
                'id' => $investment->id,
                'txid' => $investment->txid,
                'status' => $investment->status->value,
                'principal_usd' => number_format((float) $investment->amount, 2, '.', ''),
                'current_capital_usd' => number_format($current, 2, '.', ''),
            ],
            'transactions' => $paginator,
        ]);
    }
}
