<?php

namespace App\Http\Middleware;

use App\Core\Services\PluginService;
use App\Enums\RoleEnum;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckRole
{
    public function __construct(
        private PluginService $pluginService
    ) {}

    /**
     * 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 (! auth()->check()) {
            return redirect()->route('login');
        }

        $user = auth()->user();

        if (! $user->role) {
            abort(403, 'User has no role assigned.');
        }

        $userRoleSlug = $user->role->slug;

        // Super admin has access to all admin routes
        if ($userRoleSlug === RoleEnum::SUPER_ADMIN->value) {
            return $next($request);
        }

        // Check if user has one of the required roles
        foreach ($roles as $role) {
            // Normalize role slug (support both old and new formats)
            $normalizedRole = $this->normalizeRoleSlug($role);
            if ($userRoleSlug === $normalizedRole) {
                return $next($request);
            }
        }

        abort(403, 'Unauthorized action.');
    }

    /**
     * Normalize role slug (support legacy 'super-admin' and new 'super_admin')
     */
    private function normalizeRoleSlug(string $role): string
    {
        $mapping = [
            'super-admin' => RoleEnum::SUPER_ADMIN->value,
            'admin' => RoleEnum::ADMINISTRATION->value,
        ];

        return $mapping[$role] ?? $role;
    }
}
