<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Roles\AssignUserRolesRequest;
use App\Http\Requests\Roles\PermissionStoreRequest;
use App\Http\Requests\Roles\PermissionUpdateRequest;
use App\Http\Requests\Roles\RoleListRequest;
use App\Http\Requests\Roles\RolePermissionUpdateRequest;
use App\Http\Requests\Roles\RoleStoreRequest;
use App\Http\Requests\Roles\RoleUpdateRequest;
use App\Http\Requests\Roles\UserRoleListRequest;
use App\Http\Resources\Roles\PermissionResource;
use App\Http\Resources\Roles\RolePermissionResource;
use App\Http\Resources\Roles\RoleResource;
use App\Http\Resources\Roles\UserWithRolesResource;
use App\Models\Permission;
use App\Models\Role;
use App\Services\Roles\PermissionCrudService;
use App\Services\Roles\RoleAssignmentService;
use App\Services\Roles\RoleCrudService;
use App\Services\Roles\RolePermissionService;
use App\Services\Roles\RoleQueryService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class RolePermissionController extends BaseApiController
{
    public function __construct(
        private RoleQueryService $queryService,
        private RoleAssignmentService $assignmentService,
        private RolePermissionService $permissionService,
        private RoleCrudService $roleCrudService,
        private PermissionCrudService $permissionCrudService
    ) {
        parent::__construct();
    }

    public function roles(RoleListRequest $request): JsonResponse
    {
        $roles = $this->queryService->listRoles($request->validated());

        return $this->success([
            'roles' => RoleResource::collection($roles->items()),
            'meta' => [
                'total' => $roles->total(),
                'per_page' => $roles->perPage(),
                'current_page' => $roles->currentPage(),
                'last_page' => $roles->lastPage(),
            ],
        ]);
    }

    public function showRole(int $roleId): JsonResponse
    {
        $role = Role::query()->find($roleId);
        if (!$role) {
            return $this->error('Role not found.', Response::HTTP_NOT_FOUND);
        }

        return $this->success([
            'role' => new RoleResource($role),
        ]);
    }

    public function storeRole(RoleStoreRequest $request): JsonResponse
    {
        try {
            $role = $this->roleCrudService->create($request->validated());
        } catch (\Throwable $e) {
            Log::error('Role store failed: ' . $e->getMessage());
            return $this->error('Failed to create role.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success([
            'role' => new RoleResource($role),
        ], 'Role created successfully.', Response::HTTP_CREATED);
    }

    public function updateRole(RoleUpdateRequest $request, int $roleId): JsonResponse
    {
        $role = Role::query()->find($roleId);
        if (!$role) {
            return $this->error('Role not found.', Response::HTTP_NOT_FOUND);
        }

        try {
            $role = $this->roleCrudService->update($role, $request->validated());
        } catch (\Throwable $e) {
            Log::error('Role update failed: ' . $e->getMessage());
            return $this->error('Failed to update role.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success([
            'role' => new RoleResource($role),
        ], 'Role updated successfully.');
    }

    public function deleteRole(int $roleId): JsonResponse
    {
        $role = Role::query()->find($roleId);
        if (!$role) {
            return $this->error('Role not found.', Response::HTTP_NOT_FOUND);
        }

        try {
            $this->roleCrudService->delete($role);
        } catch (\Throwable $e) {
            Log::error('Role delete failed: ' . $e->getMessage());
            return $this->error('Failed to delete role.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success(null, 'Role deleted successfully.');
    }

    public function users(UserRoleListRequest $request): JsonResponse
    {
        $users = $this->queryService->listUsersWithRoles($request->validated());

        return $this->success([
            'users' => UserWithRolesResource::collection($users->items()),
            'meta' => [
                'total' => $users->total(),
                'per_page' => $users->perPage(),
                'current_page' => $users->currentPage(),
                'last_page' => $users->lastPage(),
            ],
        ]);
    }

    public function assignRoles(AssignUserRolesRequest $request, int $userId): JsonResponse
    {
        $actorId = $this->authenticatedUserIdOrUnauthorized();
        if ($actorId instanceof JsonResponse) {
            return $actorId;
        }

        try {
            $result = $this->assignmentService->assignRoles(
                $userId,
                (array) ($request->validated()['role_ids'] ?? []),
                $actorId
            );
        } catch (\Throwable $e) {
            Log::error('Assign roles failed: ' . $e->getMessage());
            return $this->error('Failed to update roles.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        if (!($result['ok'] ?? false)) {
            return $this->error($result['message'] ?? 'Failed to update roles.', Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return $this->success([
            'role_names' => $result['role_names'] ?? [],
        ], 'Roles updated successfully.');
    }

    public function permissions(): JsonResponse
    {
        $permissions = $this->permissionService->listPermissions();

        return $this->success([
            'permissions' => PermissionResource::collection($permissions),
        ]);
    }

    public function showPermission(int $permissionId): JsonResponse
    {
        $permission = Permission::query()->find($permissionId);
        if (!$permission) {
            return $this->error('Permission not found.', Response::HTTP_NOT_FOUND);
        }

        return $this->success([
            'permission' => new PermissionResource($permission),
        ]);
    }

    public function storePermission(PermissionStoreRequest $request): JsonResponse
    {
        try {
            $permission = $this->permissionCrudService->create($request->validated());
        } catch (\Throwable $e) {
            Log::error('Permission store failed: ' . $e->getMessage());
            return $this->error('Failed to create permission.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success([
            'permission' => new PermissionResource($permission),
        ], 'Permission created successfully.', Response::HTTP_CREATED);
    }

    public function updatePermission(PermissionUpdateRequest $request, int $permissionId): JsonResponse
    {
        $permission = Permission::query()->find($permissionId);
        if (!$permission) {
            return $this->error('Permission not found.', Response::HTTP_NOT_FOUND);
        }

        try {
            $permission = $this->permissionCrudService->update($permission, $request->validated());
        } catch (\Throwable $e) {
            Log::error('Permission update failed: ' . $e->getMessage());
            return $this->error('Failed to update permission.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success([
            'permission' => new PermissionResource($permission),
        ], 'Permission updated successfully.');
    }

    public function deletePermission(int $permissionId): JsonResponse
    {
        $permission = Permission::query()->find($permissionId);
        if (!$permission) {
            return $this->error('Permission not found.', Response::HTTP_NOT_FOUND);
        }

        try {
            $this->permissionCrudService->delete($permission);
        } catch (\Throwable $e) {
            Log::error('Permission delete failed: ' . $e->getMessage());
            return $this->error('Failed to delete permission.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success(null, 'Permission deleted successfully.');
    }

    public function rolePermissions(int $roleId): JsonResponse
    {
        $rows = $this->permissionService->listRolePermissions($roleId);

        return $this->success([
            'permissions' => RolePermissionResource::collection($rows),
        ]);
    }

    public function updateRolePermissions(RolePermissionUpdateRequest $request, int $roleId): JsonResponse
    {
        try {
            $this->permissionService->saveRolePermissions($roleId, $request->validated()['permissions'] ?? []);
        } catch (\Throwable $e) {
            Log::error('Role permissions update failed: ' . $e->getMessage());
            return $this->error('Failed to update role permissions.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success(null, 'Permissions saved successfully.');
    }

    /**
     * @return int|JsonResponse
     */
    private function authenticatedUserIdOrUnauthorized(): int|JsonResponse
    {
        $userId = (int) (auth()->id() ?? 0);
        if ($userId <= 0) {
            return $this->error('Unauthorized.', Response::HTTP_UNAUTHORIZED);
        }

        return $userId;
    }
}
