<?php

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

use App\Lottery\ErrorCode;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\AdminCaptchaService;

/**
 * E2E 辅助：peek captcha bypass 码。
 *
 * digest 是 HMAC(app.key) 单向，存进 cache 的就是 digest，无法反查明文。
 * 改用 e2e 约定：captcha_code == "LOTTERY_E2E_BYPASS" 在 LOTTERY_E2E=true 时视为通过。
 * 本端点不返回任何"答案"，仅返回约定码提示。
 */
final class E2ECaptchaPeekController extends Controller
{
    public function player(Request $request): JsonResponse
    {
        $key = (string) $request->input('captcha_key', '');
        if ($key === '') {
            return ApiResponse::error('captcha_key required', ErrorCode::ValidationFailed->value, null, 422);
        }

        return $this->peek($key, AdminCaptchaService::SCOPE_PLAYER);
    }

    public function admin(Request $request): JsonResponse
    {
        $key = (string) $request->input('captcha_key', '');
        if ($key === '') {
            return ApiResponse::error('captcha_key required', ErrorCode::ValidationFailed->value, null, 422);
        }

        return $this->peek($key, AdminCaptchaService::SCOPE_ADMIN);
    }

    private function peek(string $key, string $scope): JsonResponse
    {
        return ApiResponse::success([
            'bypass_code' => 'LOTTERY_E2E_BYPASS',
            'scope' => $scope,
            'key' => $key,
            'hint' => 'POST captcha_code=LOTTERY_E2E_BYPASS to login when LOTTERY_E2E=true',
        ]);
    }
}
