<?php

namespace App\Http\Middleware;

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

class RoleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  ...$roles
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle(Request $request, Closure $next, ...$roles): Response
    {
        // 1. Cek apakah sudah login
        if (!Auth::check()) {
            return redirect()->route('login');
        }

        $userRole = Auth::user()->role;

        // 2. Cek apakah role user ada dalam daftar yang diizinkan
        if (in_array($userRole, $roles)) {
            return $next($request);
        }

        // 3. Jika tidak punya akses, arahkan menggunakan switch (Ganti dari match)
        switch ($userRole) {
            case 'admin':
                return redirect()->route('admin.dashboard');
            case 'courier':
                return redirect()->route('courier.dashboard');
            default:
                return redirect()->route('user.dashboard');
        }
    }
}