package com.example.dateplanner.services;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Map;

@Slf4j
@Service
public class TurnstileService {

    @Value("${turnstile.secret-key}")
    private String secretKey;

    @Value("${turnstile.enabled:true}")
    private boolean enabled;

    private final WebClient webClient = WebClient.builder()
            .baseUrl("https://challenges.cloudflare.com")
            .build();

    @SuppressWarnings("unchecked")
    public Mono<Boolean> verify(String token) {
        if (!enabled) {
            return Mono.just(true);
        }
        if (token == null || token.isBlank()) {
            return Mono.just(false);
        }
        return webClient.post()
                .uri("/turnstile/v0/siteverify")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .body(BodyInserters.fromFormData("secret", secretKey).with("response", token))
                .retrieve()
                .bodyToMono(Map.class)
                .map(body -> Boolean.TRUE.equals(body.get("success")))
                .onErrorResume(e -> {
                    log.error("Turnstile verification error: {}", e.getMessage());
                    return Mono.just(false);
                });
    }
}
