<?php

namespace Modules\Auth\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Services\ActiveRoleService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\Auth\Transformers\UserResource;

class SessionController extends Controller
{
    /**
     * Current authenticated user with active role metadata.
     */
    public function currentUser(Request $request): JsonResponse
    {
        $user = $request->user();

        if (! $user) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthenticated',
            ], 401);
        }

        $user->load(['roles.permissions']);

        return response()->json([
            'success' => true,
            'data' => new UserResource($user),
            ...ActiveRoleService::sessionMeta($user),
        ]);
    }

    /**
     * Switch active role for the current session token.
     */
    public function switchRole(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'role_id' => ['required', 'uuid', 'exists:roles,id'],
        ]);

        $user = $request->user();
        $user->load(['roles.permissions']);

        $role = ActiveRoleService::switchRole($user, $validated['role_id']);

        if (! $role) {
            return response()->json([
                'success' => false,
                'message' => 'Peranan tidak ditetapkan untuk pengguna ini.',
            ], 403);
        }

        return response()->json([
            'success' => true,
            'message' => 'Peranan aktif dikemas kini.',
            'data' => new UserResource($user),
            'active_role' => ActiveRoleService::formatRole($role),
            'can_switch_role' => $user->roles->count() > 1,
            'redirect_path' => ActiveRoleService::redirectPathForRole($role),
        ]);
    }
}
