<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Roles\RoleSwitchRequest;
use App\Services\Roles\RoleSwitchService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class RoleSwitcherController extends BaseApiController
{
    public function __construct(private RoleSwitchService $switchService)
    {
        parent::__construct();
    }

    public function index(): JsonResponse
    {
        $userId = (int) (auth()->id() ?? 0);
        if ($userId <= 0) {
            return $this->error('Please log in first.', Response::HTTP_UNAUTHORIZED);
        }

        $roles = $this->switchService->getUserRoleNames($userId);
        if (empty($roles)) {
            return $this->error('No roles assigned to this user.', Response::HTTP_NOT_FOUND);
        }

        return $this->success([
            'roles' => $roles,
        ]);
    }

    public function switch(RoleSwitchRequest $request): JsonResponse
    {
        $role = (string) $request->validated()['role'];
        $route = $this->switchService->switchRole($role);

        return $this->success([
            'role' => $role,
            'dashboard_route' => $route,
        ], 'Role switched successfully.');
    }
}
