<?php

namespace Kylin\Auth\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Auth\Requests\LoginRequest;
use Kylin\Auth\Requests\RegisterRequest;
use Kylin\Auth\Services\AuthService;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;

/**
 * 认证控制器
 *
 * 提供登录、注册、退出、Token 刷新等认证 API。
 */
class AuthController extends BaseController
{
    public function __construct(
        private readonly AuthService $authService,
    ) {}

    public function login(LoginRequest $request): JsonResponse
    {
        try {
            $result = $this->authService->login(
                $request->validated('account'),
                $request->validated('password'),
                $request->validated('captcha_key'),
                $request->validated('captcha_code'),
            );
            return ApiResponse::success($result, '登录成功');
        } catch (\Kylin\Auth\Exceptions\AuthException $e) {
            return ApiResponse::error(code: $e->errorCode()->value(), message: $e->getMessage(), httpStatus: $e->getHttpStatusCode());
        } catch (\Throwable $e) {
            \Illuminate\Support\Facades\Log::error('登录异常', ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return ApiResponse::error(code: 'AUTH-ERR', message: '登录失败: ' . $e->getMessage(), httpStatus: 500);
        }
    }

    public function register(RegisterRequest $request): JsonResponse
    {
        $result = $this->authService->register(
            $request->validated('account'),
            $request->validated('password'),
            $request->validated('nickname'),
        );
        return ApiResponse::created($result, '注册成功');
    }

    public function logout(Request $request): JsonResponse
    {
        $this->authService->logout($request->user());
        return ApiResponse::success(null, '已退出登录');
    }

    public function me(Request $request): JsonResponse
    {
        $user = $this->authService->me($request->user());
        return ApiResponse::success($user);
    }

    public function refresh(Request $request): JsonResponse
    {
        $token = $this->authService->refreshToken($request->user());
        return ApiResponse::success(['token' => $token, 'token_type' => 'Bearer']);
    }

    public function captcha(): JsonResponse
    {
        $captcha = $this->authService->generateCaptcha();
        return ApiResponse::success($captcha);
    }
}
