<?php

namespace Kylin\User\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;
use Kylin\User\Models\User;
use Kylin\User\Requests\StoreUserRequest;
use Kylin\User\Requests\UpdateUserRequest;
use Kylin\User\Services\UserService;

/**
 * 用户控制器
 *
 * 提供用户 CRUD、状态管理、资料管理等 API。
 *
 * 合规要求：
 *  - 依据等保 2.0 (GB/T 22239) 8.1.4.1，使用 UserPolicy 控制访问权限
 */
class UserController extends BaseController
{
    public function __construct(
        private readonly UserService $userService,
    ) {}

    public function index(Request $request): JsonResponse
    {
        $this->authorize('viewAny', User::class);

        $users = $this->userService->list(
            $request->only(['keyword', 'status']),
            $request->input('per_page', 15),
        );
        return ApiResponse::paginate($users);
    }

    public function store(StoreUserRequest $request): JsonResponse
    {
        $this->authorize('create', User::class);

        $user = $this->userService->create($request->validated());
        return ApiResponse::created($user->load('profile', 'roles'));
    }

    public function show(int $user): JsonResponse
    {
        $userModel = User::with(['profile', 'roles', 'permissions'])->findOrFail($user);

        $this->authorize('view', $userModel);

        return ApiResponse::success($userModel);
    }

    public function update(UpdateUserRequest $request, int $user): JsonResponse
    {
        $userModel = User::findOrFail($user);

        $this->authorize('update', $userModel);

        $updated = $this->userService->update($userModel, $request->validated());
        return ApiResponse::success($updated->load('profile', 'roles'));
    }

    public function destroy(int $user): JsonResponse
    {
        $userModel = User::findOrFail($user);

        $this->authorize('delete', $userModel);

        $this->userService->delete($userModel);
        return ApiResponse::success(null, '删除成功');
    }
}