<?php

namespace App\Http\Controllers\Api\V1\Identity;

use App\Domain\Identity\Models\Role;
use App\Domain\Identity\Models\User;
use App\Domain\Identity\Services\PermissionScopeResolver;
use App\Http\Controllers\Controller;
use App\Http\Requests\Identity\SyncRoleUsersRequest;
use App\Http\Resources\UserResource;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoleUserController extends Controller
{
    public function __construct(private readonly PermissionScopeResolver $resolver) {}

    public function index(Request $request, Role $role): JsonResponse
    {
        $this->authorize('view', $role);

        $users = $role->users()
            ->with(['company:id,uuid,name', 'branch:id,uuid,name'])
            ->orderBy('name')
            ->paginate($request->integer('per_page', 25));

        return ApiResponse::success(UserResource::collection($users));
    }

    public function sync(SyncRoleUsersRequest $request, Role $role): JsonResponse
    {
        $this->authorize('assignUsers', $role);

        $users = User::whereIn('uuid', $request->input('users'))->get();
        $attaching = $request->input('action') === 'attach';

        DB::transaction(function () use ($users, $role, $attaching) {
            foreach ($users as $user) {
                $attaching ? $user->assignRole($role) : $user->removeRole($role);
                $this->resolver->forget($user);
            }
        });

        return ApiResponse::success(
            ['affected' => $users->count()],
            $attaching ? 'Users assigned to role.' : 'Users removed from role.',
        );
    }
}
