<?php

namespace App\Http\Middleware;

use App\Enums\Role;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserHasRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        if (! $request->user()) {
            // For Inertia requests, redirect to login
            if ($request->header('X-Inertia')) {
                return redirect()->route('login');
            }
            abort(401, 'Unauthenticated.');
        }

        $userRole = $request->user()->role;

        $allowedRoles = array_map(fn (string $role) => Role::from($role), $roles);

        if (! in_array($userRole, $allowedRoles, true)) {
            // Log role mismatch for debugging
            \Log::warning('EnsureUserHasRole - Role Mismatch', [
                'user_id' => $request->user()->id,
                'user_role' => $userRole->value,
                'required_roles' => array_map(fn ($r) => $r->value, $allowedRoles),
                'url' => $request->fullUrl(),
                'method' => $request->method(),
                'is_inertia' => $request->header('X-Inertia'),
            ]);
            
            // For Inertia requests, redirect to appropriate dashboard
            if ($request->header('X-Inertia')) {
                return match ($userRole) {
                    Role::Admin => redirect('/admin/dashboard'),
                    Role::Partner => redirect('/partner/dashboard'),
                    Role::User => redirect('/dashboard'),
                    default => redirect('/login'),
                };
            }
            abort(403, 'Unauthorized. Required role: '.implode(', ', $roles));
        }

        return $next($request);
    }
}

