package dev.rheinsw.server.contact.util;

import dev.rheinsw.server.contact.model.HCaptchaConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author Thatsaphorn Atchariyaphap
 * @since 21.04.25
 */
@Service
public class HCaptchaValidator {
    private static final Logger log = LoggerFactory.getLogger(HCaptchaValidator.class);

    private final HCaptchaConfig config;
    private final RestTemplate restTemplate;

    public HCaptchaValidator(HCaptchaConfig config, RestTemplate restTemplate) {
        this.config = config;
        this.restTemplate = restTemplate;
    }

    public boolean isValid(String token) {
        if (token == null || token.isBlank()) {
            log.warn("Captcha token is missing or blank");
            return false;
        }

        String secret = config.getSecret();
        if (secret == null || secret.isBlank()) {
            log.error("Captcha secret is missing");
            return false;
        }

        try {
            var response = restTemplate.postForObject(
                    "https://api.hcaptcha.com/siteverify",
                    new org.springframework.util.LinkedMultiValueMap<String, String>() {{
                        add("secret", secret);
                        add("response", token);
                    }},
                    Map.class
            );

            return response != null && Boolean.TRUE.equals(response.get("success"));
        } catch (Exception e) {
            log.error("Failed to verify hCaptcha", e);
            return false;
        }
    }
}
