<?php

namespace App\Services\Roles;

use App\Models\UserRole;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class RoleSwitchService
{
    public function __construct(private RoleDashboardService $dashboardService)
    {
    }

    public function getUserRoleNames(int $userId): array
    {
        $roles = UserRole::getRolesByUserId($userId);
        return array_values(array_filter(array_map(fn ($r) => (string) ($r['role_name'] ?? ''), $roles)));
    }

    public function switchRole(int $userId, string $role): string
    {
        $requested = strtolower(trim($role));
        if ($requested === '') {
            throw new NotFoundHttpException('Role not found.');
        }

        $roles = $this->getUserRoleNames($userId);
        $matchedRole = null;

        foreach ($roles as $assignedRole) {
            $normalized = strtolower(trim($assignedRole));
            if ($normalized === $requested) {
                $matchedRole = $assignedRole;
                break;
            }
        }

        if ($matchedRole === null) {
            throw new AccessDeniedHttpException('Invalid role selected.');
        }

        session()->put('role', $matchedRole);

        return $this->dashboardService->bestDashboardRouteFor([$matchedRole]);
    }
}
