<?php

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

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\RoleManagement\StoreRoleRequest;
use App\Http\Requests\Api\V1\RoleManagement\UpdateRoleRequest;
use App\Http\Resources\Api\V1\RoleResource;
use App\Services\RoleService;
use App\Services\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    protected RoleService $roleService;
    protected ResponseService $responseService;

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

    public function index(): JsonResponse
    {
        try {
            $roles = $this->roleService->getAllRoles();

            return $this->responseService->success(
                RoleResource::collection($roles),
                'Roles retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to retrieve roles', $e->getMessage());
        }
    }

    public function store(StoreRoleRequest $request): JsonResponse
    {
        try {
            $role = $this->roleService->createRole($request->validated());

            return $this->responseService->created(
                new RoleResource($role),
                'Role created successfully'
            );
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to create role', $e->getMessage());
        }
    }

    public function show(int $id): JsonResponse
    {
        try {
            $role = $this->roleService->getRole($id);

            return $this->responseService->success(
                new RoleResource($role),
                'Role retrieved successfully'
            );
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->responseService->notFound('Role not found');
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to retrieve role', $e->getMessage());
        }
    }

    public function update(UpdateRoleRequest $request, int $id): JsonResponse
    {
        try {
            $role = $this->roleService->updateRole($id, $request->validated());

            return $this->responseService->success(
                new RoleResource($role),
                'Role updated successfully'
            );
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->responseService->notFound('Role not found');
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to update role', $e->getMessage());
        }
    }

    public function destroy(int $id): JsonResponse
    {
        try {
            $this->roleService->deleteRole($id);

            return $this->responseService->noContent('Role deleted successfully');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->responseService->notFound('Role not found');
        } catch (\Exception $e) {
            return $this->responseService->error($e->getMessage(), 400);
        }
    }

    public function syncPermissions(Request $request, int $id): JsonResponse
    {
        try {
            $request->validate([
                'permissions' => ['required', 'array'],
                'permissions.*' => ['string', 'exists:permissions,name'],
            ]);

            $role = $this->roleService->syncPermissions($id, $request->input('permissions'));

            return $this->responseService->success(
                new RoleResource($role),
                'Permissions synced successfully'
            );
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->responseService->notFound('Role not found');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->responseService->validationError($e->errors());
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to sync permissions', $e->getMessage());
        }
    }

    public function permissions(int $id): JsonResponse
    {
        try {
            $permissions = $this->roleService->getRolePermissions($id);

            return $this->responseService->success(
                $permissions->pluck('name'),
                'Role permissions retrieved successfully'
            );
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->responseService->notFound('Role not found');
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to retrieve permissions', $e->getMessage());
        }
    }
}
