<?php

namespace App\Http\Middleware;

use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class RedirectIfAuthenticated
{
    public function handle(Request $request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                return $this->redirectToPanel(Auth::guard($guard)->user()->role);
            }
        }

        return $next($request);
    }

    protected function redirectToPanel(string $role)
    {
        return match($role) {
            'farmer' => redirect()->route('farmer.panel'),
            'admin' => redirect()->route('admin.panel'),
            'contractor' => redirect()->route('contractor.panel'),
            'transporter' => redirect()->route('transporter.panel'),
            'factory_receiver' => redirect()->route('factory.reciever.panel'),
            'chief_worker' => redirect()->route('chief.panel'),
            'worker' => redirect()->route('worker.panel'),
            'dryer' => redirect()->route('dryer.panel'),
            'packager' => redirect()->route('pack.panel'),
            'distributor' => redirect()->route('distributor.panel'),
            default => redirect()->route('login')
        };
    }
}
