<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureTraderAccount
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (! $user) {
            return redirect()->route('login');
        }

        if ($user->isAdmin()) {
            return redirect()
                ->route('admin.dashboard')
                ->with('error', 'Admin accounts are for platform management only. Please use a normal user account to access trader features.');
        }

        if ($user->isSupportTeam()) {
            return redirect()
                ->route('support-team.dashboard')
                ->with('error', 'Support team accounts are for ticket management only. Please use a normal user account to access trader features.');
        }

        if ($user->isMentor()) {
            return redirect()
                ->route('mentor.dashboard')
                ->with('error', 'Mentor accounts are for managing students. Please use a student or normal user account to access trader features.');
        }

        if (! $user->isTrader()) {
            return redirect()
                ->route('login')
                ->withErrors(['email' => 'Your account cannot access trader features right now. Please contact support.']);
        }

        return $next($request);
    }
}
