<?php

namespace App\Http\Controllers;

use App\Models\InvestmentDuration;
use App\Models\InvestmentSetting;
use App\Services\EmailActionConfirmation;
use App\Support\InvestmentLedger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;

class InvestmentController extends Controller
{
    /**
     * Show the investment configuration page.
     */
    public function index(Request $request): Response
    {
        $withdrawable = InvestmentLedger::totalWithdrawableForUser((int) $request->user()->id);

        return Inertia::render('investments/index', [
            'settings' => InvestmentSetting::current(),
            'withdrawable_balance_usd' => number_format($withdrawable, 2, '.', ''),
            'reinvest_mode' => $request->boolean('reinvertir'),
            'durations' => InvestmentDuration::query()
                ->where('is_active', true)
                ->orderBy('sort_order')
                ->orderBy('months')
                ->get(['id', 'months', 'label']),
        ]);
    }

    /**
     * Store a pending investment via blockchain (txid) or an active investment funded from withdrawable balance.
     */
    public function store(Request $request, EmailActionConfirmation $emailConfirmation): RedirectResponse
    {
        $settings = InvestmentSetting::current();

        $fundingSource = (string) $request->input('funding_source');
        $amountMin = $fundingSource === 'balance' ? 0.01 : (float) $settings->min_amount;

        $validated = $request->validate([
            'funding_source' => ['required', 'string', Rule::in(['blockchain', 'balance'])],
            'amount' => ['required', 'numeric', 'min:'.$amountMin, 'max:'.$settings->max_amount],
            'duration_months' => [
                'required',
                'integer',
                Rule::exists('investment_durations', 'months')->where('is_active', true),
            ],
            'txid' => [
                Rule::requiredIf(($request->input('funding_source') ?? '') === 'blockchain'),
                'nullable',
                'string',
                'max:191',
                Rule::unique('investments', 'txid'),
            ],
        ]);

        $user = $request->user();

        if ($validated['funding_source'] === 'balance') {
            $available = InvestmentLedger::totalWithdrawableForUser((int) $user->id);

            if ($available <= 0) {
                throw ValidationException::withMessages([
                    'amount' => ['No tienes capital disponible para retirar (recuerda: el principal permanece bloqueado hasta el vencimiento).'],
                ]);
            }

            if ((float) $validated['amount'] > $available + 0.0001) {
                throw ValidationException::withMessages([
                    'amount' => ['La solicitud supera tu capital disponible consolidado.'],
                ]);
            }

            $emailConfirmation->sendInvestmentFromBalance(
                $user,
                (float) $validated['amount'],
                (int) $validated['duration_months'],
            );

            Inertia::flash('toast', [
                'type' => 'success',
                'message' => 'Te enviamos un correo: confirma la inversión con el enlace para debitar tu saldo retirable.',
            ]);

            return to_route('investments.index');
        }

        $emailConfirmation->sendInvestmentFromBlockchain(
            $user,
            (float) $validated['amount'],
            (int) $validated['duration_months'],
            trim((string) $validated['txid']),
        );

        Inertia::flash('toast', [
            'type' => 'success',
            'message' => 'Revisa tu correo: confirma la inversión para registrar el depósito pendiente de revisión.',
        ]);

        return to_route('investments.index');
    }
}
