<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\Api\V1\UserResource;
use App\Services\UserService;
use App\Services\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserController extends Controller
{
    protected UserService $userService;
    protected ResponseService $responseService;

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

    public function index(Request $request): JsonResponse
    {
        try {
            $perPage = $request->input('per_page', 15);
            $users = $this->userService->getAllUsers($perPage);

            return $this->responseService->paginated(
                $users,
                'Users retrieved successfully',
                UserResource::class
            );
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to retrieve users', $e->getMessage());
        }
    }

    public function show(int $id): JsonResponse
    {
        try {
            $user = $this->userService->getUser($id);

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

    public function assignRole(Request $request, int $id): JsonResponse
    {
        try {
            $request->validate([
                'role' => ['required', 'string', 'exists:roles,name'],
            ]);

            $user = $this->userService->assignRole($id, $request->input('role'));

            return $this->responseService->success(
                new UserResource($user),
                'Role assigned successfully'
            );
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->responseService->notFound('User not found');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->responseService->validationError($e->errors());
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to assign role', $e->getMessage());
        }
    }

    public function revokeRole(Request $request, int $id): JsonResponse
    {
        try {
            $request->validate([
                'role' => ['required', 'string', 'exists:roles,name'],
            ]);

            $user = $this->userService->revokeRole($id, $request->input('role'));

            return $this->responseService->success(
                new UserResource($user),
                'Role revoked successfully'
            );
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->responseService->notFound('User not found');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->responseService->validationError($e->errors());
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to revoke role', $e->getMessage());
        }
    }

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

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

    public function store(Request $request): JsonResponse
    {
        try {
            $validated = $request->validate([
                'name' => ['required', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'password' => ['required', 'string', 'min:6', 'confirmed'],
                'branch_id' => ['nullable', 'integer', 'exists:branches,id'],
                'roles' => ['nullable', 'array'],
                'roles.*' => ['string', 'exists:roles,name'],
            ]);

            $user = $this->userService->createUser($validated);

            return $this->responseService->created(
                new UserResource($user),
                'User created successfully'
            );
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->responseService->validationError($e->errors());
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to create user', $e->getMessage());
        }
    }

    public function update(Request $request, int $id): JsonResponse
    {
        try {
            $validated = $request->validate([
                'name' => ['sometimes', 'string', 'max:255'],
                'email' => ['sometimes', 'string', 'email', 'max:255', 'unique:users,email,' . $id],
                'password' => ['sometimes', 'string', 'min:6', 'confirmed'],
                'branch_id' => ['nullable', 'integer', 'exists:branches,id'],
                'roles' => ['nullable', 'array'],
                'roles.*' => ['string', 'exists:roles,name'],
            ]);

            $user = $this->userService->updateUser($id, $validated);

            return $this->responseService->success(
                new UserResource($user),
                'User updated successfully'
            );
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->responseService->notFound('User not found');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->responseService->validationError($e->errors());
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to update user', $e->getMessage());
        }
    }

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

            return $this->responseService->success(
                null,
                'User deleted successfully'
            );
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->responseService->notFound('User not found');
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to delete user', $e->getMessage());
        }
    }
}
