<?php

namespace App\Shared\Captcha;

use App\Shared\Constant\ErrorCodes;
use App\Shared\Exception\AppException;
use Symfony\Component\HttpFoundation\Request;

/**
 * Drop-in captcha check for public endpoints.
 *
 * Call `assertValid($request)` at the top of any unauthenticated POST handler.
 * No-op when ALTCHA is disabled (dev/test), so protected handlers stay testable
 * without solving a proof-of-work.
 */
class CaptchaGuard
{
    public function __construct(private readonly AltchaService $altcha) {}

    public function assertValid(Request $request): void
    {
        if (!$this->altcha->enabled()) {
            return;
        }

        $data    = json_decode($request->getContent(), true);
        $payload = is_array($data) ? (string) ($data['altcha'] ?? '') : '';

        if (!$this->altcha->verifySolution($payload)) {
            throw new AppException(ErrorCodes::ERR_CAPTCHA_001, null, 422, 'altcha');
        }
    }
}
