package com.astalange.core.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Map;

@Service
public class CaptchaValidationService {

    @Value("${captcha.secret:1x0000000000000000000000000000000AA}")
    private String captchaSecret;

    @Value("${captcha.url:https://challenges.cloudflare.com/turnstile/v0/siteverify}")
    private String captchaUrl;

    public boolean validateCaptcha(String token) {
        if (token == null || token.isEmpty()) {
            return false;
        }

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("secret", captchaSecret);
        map.add("response", token);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(captchaUrl, request, Map.class);
            if (response.getBody() != null && Boolean.TRUE.equals(response.getBody().get("success"))) {
                return true;
            }
        } catch (Exception e) {
            // Log error
            return false;
        }
        return false;
    }
}
