<?php

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

use App\Exceptions\PlayerAuthenticationException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Player\PlayerAuthLoginRequest;
use App\Lottery\ErrorCode;
use App\Services\AdminCaptchaService;
use App\Services\Player\PlayerNativeAuthService;
use App\Support\ApiResponse;
use App\Support\LotteryMessage;
use Illuminate\Http\JsonResponse;

/** POST /api/v1/player/auth/login — 代理线下玩家账号密码登录 */
final class PlayerAuthLoginController extends Controller
{
    public function __invoke(
        PlayerAuthLoginRequest $request,
        PlayerNativeAuthService $auth,
        AdminCaptchaService $captcha,
    ): JsonResponse {
        $data = $request->validated();

        if (! $captcha->verify($data['captcha_key'], $data['captcha_code'], AdminCaptchaService::SCOPE_PLAYER)) {
            return ApiResponse::error(
                LotteryMessage::sso($request, ErrorCode::PlayerCaptchaInvalid->value),
                ErrorCode::PlayerCaptchaInvalid->value,
                null,
                422,
            );
        }

        try {
            $data = $auth->login(
                (string) $request->validated('site_code', ''),
                (string) $request->validated('username'),
                (string) $request->validated('password'),
            );
        } catch (PlayerAuthenticationException $e) {
            return ApiResponse::error(
                LotteryMessage::sso($request, $e->lotteryCode),
                $e->lotteryCode,
                null,
                $e->httpStatus,
            );
        }

        return ApiResponse::success($data);
    }
}
