package ru.soune.nocopy.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
@Slf4j
public class YooKassaClient {

    @Value("${yookassa.shop-id}")
    private String shopId;

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

    private final HttpClient httpClient = HttpClient.newHttpClient();

    private final ObjectMapper mapper = new ObjectMapper();

    public boolean createAutoPayment(String paymentMethodId, double amount, String description, String userId) {
        try {
            String url = "https://api.yookassa.ru/v3/payments";
            String auth = shopId + ":" + secretKey;
            String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));

            Map<String, Object> body = new HashMap<>();
            body.put("amount", Map.of("value", String.format("%.2f", amount),
                    "currency", "RUB"));
            body.put("payment_method_id", paymentMethodId);
            body.put("description", description);
            body.put("capture", true);
            body.put("metadata", Map.of("user_id", userId, "auto_payment", "true"));

            String requestBody = mapper.writeValueAsString(body);

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Basic " + encodedAuth)
                    .header("Idempotence-Key", UUID.randomUUID().toString())
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200 || response.statusCode() == 201) {
                log.info("Auto payment created: {}", response.body());
                return true;
            } else {
                log.error("Auto payment failed: {} - {}", response.statusCode(), response.body());
                return false;
            }
        } catch (Exception e) {
            log.error("Error creating auto payment", e);
            return false;
        }
    }
}
