<?php

namespace App\Http\Middleware;

use App\Models\InvestmentSetting;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Portal inversionista: algunas acciones exigen KYC aprobado según parámetros globales.
 *
 * Parámetros del alias: `invest`, `withdraw`, `wallet`.
 */
class EnsureInvestorKycApproved
{
    /**
     * @param  Closure(Request): (Response)  $next
     * @param  'invest'|'withdraw'|'wallet'  $policy
     */
    public function handle(Request $request, Closure $next, string $policy = 'wallet'): Response
    {
        $user = $request->user();

        if ($user === null) {
            return $next($request);
        }

        $settings = InvestmentSetting::current();

        $requiresKyc = match ($policy) {
            'invest' => $settings->require_kyc_to_invest,
            'withdraw' => $settings->require_kyc_to_withdraw,
            'wallet' => true,
            default => true,
        };

        if (! $requiresKyc) {
            return $next($request);
        }

        if ($user->investorPortalUnlocked()) {
            return $next($request);
        }

        return redirect()->route('kyc.show');
    }
}
