<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class RoleMiddleware
{
    
    public function handle(Request $request, Closure $next, ...$roles)
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }

        $user = Auth::user();
        
        if (empty($roles) || in_array($user->role, $roles)) {
            return $next($request);
        }

        return $this->redirectToRolePanel($user->role);
    }

    protected function redirectToRolePanel(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')
        };
    }
}
