<?php

namespace App\Http\Middleware;

use App\Enum\UserKycStatus;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class UserKycVerification
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = Auth::user();

        if ($user->kyc_status->value === UserKycStatus::PENDING->value || $user->kyc_status->value === UserKycStatus::REJECTED->value) {
            if (
                $request->routeIs('user.transaction.*') ||
                $request->routeIs('user.deposit.*') ||
                $request->routeIs('user.withdraw.*') ||
                $request->routeIs('user.premium.*') ||
                $request->routeIs('user.profile.password') ||
                $request->routeIs('user.profile.2fa') ||
                $request->routeIs('user.trade.*') ||
                $request->routeIs('user.plan.*') ||
                $request->routeIs('user.copy.trade.*') ||
                $request->routeIs('user.swap.*') ||
                $request->routeIs('user.wallet.*')
            ) {
                return redirect()->route('user.profile.kyc')
                    ->with('error', 'Please complete your KYC verification to continue.');
            }
        } elseif ($user->kycPendingAndHasDocument()) {
            if (
                $request->routeIs('user.transaction.*') ||
                $request->routeIs('user.deposit.*') ||
                $request->routeIs('user.withdraw.*') ||
                $request->routeIs('user.premium.*') ||
                $request->routeIs('user.profile.password') ||
                $request->routeIs('user.profile.2fa') ||
                $request->routeIs('user.trade.*') ||
                $request->routeIs('user.plan.*') ||
                $request->routeIs('user.copy.trade.*') ||
                $request->routeIs('user.swap.*') ||
                $request->routeIs('user.wallet.*')
            ) {
                return redirect()->route('user.profile.kyc')
                    ->with('error', 'Your KYC documents are under review. You will be notified once approved.');
            }
        }

        return $next($request);
    }
}
