<?php

namespace App\Http\Controllers;

use App\Enums\EmailConfirmationType;
use App\Models\EmailConfirmationToken;
use App\Services\EmailConfirmationExecutor;
use Illuminate\Http\RedirectResponse;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;

class EmailConfirmationController extends Controller
{
    public function investment(string $token, EmailConfirmationExecutor $executor): RedirectResponse|Response
    {
        $record = EmailConfirmationToken::findValidByPlain($token);
        if ($record === null) {
            return $this->invalid();
        }

        try {
            $executor->fulfillInvestment($record);
        } catch (ValidationException $e) {
            return $this->validationRedirect($e);
        }

        return Inertia::render('confirmations/investment', [
            'pending_approval' => $record->typeEnum() === EmailConfirmationType::InvestmentBlockchain,
            'authenticated' => auth()->check(),
        ]);
    }

    public function withdrawal(string $token, EmailConfirmationExecutor $executor): RedirectResponse
    {
        $record = EmailConfirmationToken::findValidByPlain($token);
        if ($record === null) {
            return $this->invalid();
        }

        try {
            $executor->fulfillWithdrawal($record);
        } catch (ValidationException $e) {
            return $this->validationRedirect($e);
        }

        Inertia::flash('toast', [
            'type' => 'success',
            'message' => 'Solicitud de retiro confirmada. El equipo la revisará en breve.',
        ]);

        if (auth()->check()) {
            return redirect()->route('balances.index');
        }

        return redirect()->route('login');
    }

    private function invalid(): RedirectResponse
    {
        Inertia::flash('toast', [
            'type' => 'error',
            'message' => 'El enlace no es válido o expiró.',
        ]);

        return redirect()->route(auth()->check() ? 'dashboard' : 'login');
    }

    private function validationRedirect(ValidationException $e): RedirectResponse
    {
        $first = $e->errors()['token'][0] ?? 'No se pudo completar la confirmación.';

        Inertia::flash('toast', [
            'type' => 'error',
            'message' => $first,
        ]);

        return redirect()->route(auth()->check() ? 'dashboard' : 'login');
    }
}
