<?php

namespace Modules\Auth\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Modules\Auth\Http\Requests\Role\UpdateRolePermissionsRequest;
use Modules\Auth\Models\Role;
use Modules\Auth\Services\RoleService;
use Modules\Auth\Transformers\RoleResource;
use Modules\Core\Helpers\ApiResponse;

class RoleController extends Controller
{
    use AuthorizesRequests;

    protected $roleService;

    public function __construct(RoleService $roleService)
    {
        $this->roleService = $roleService;
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $this->authorize('viewAny', Role::class);

        $roles = $this->roleService->getAllRoles();

        return ApiResponse::successResponse(
            message: 'Roles retrieved successfully.',
            data: $roles
        );
    }

    /**
     * Show the specified resource.
     */
    public function rolePermissions(Role $role)
    {
        $this->authorize('updateRolePermissions', $role);

        return ApiResponse::successResponse(
            message: 'Role & permissions retrieved successfully.',
            data: [
                'role' => $role->only('id', 'title'),
                'permissions' => $this->roleService->getForRole($role),
            ]
        );
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateRolePermissionsRequest $request, Role $role)
    {
        $this->authorize('updateRolePermissions', $role);

        $validated = $request->validated();

        $role = $this->roleService->updateRoleWithPermissions(
                $role,
                $validated['title'],
                $validated['permissions'] ?? []
            );

        return ApiResponse::successResponse(
            message: 'Role & permissions updated successfully.',
            data: new RoleResource($role)
        );
    }

    /**
     * Look up roles.
     */
    public function rolesList()
    {
        $roles = $this->roleService->getRoleList();

        return ApiResponse::successResponse(
            message: 'Roles list retrieved successfully.',
            data: $roles
        );
    }
}
