package io.wdd.pusher;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.wdd.pusher.beans.NtfyReceiveMessage;
import io.wdd.pusher.beans.PushMessageType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Service
@Slf4j
public class MessagePusher {

    @Resource
    ObjectMapper objectMapper;
    @Value("${octopus.notify.pusher_url}")
    String pushServerUrl;

    public NtfyReceiveMessage Send(Object sendMessage, PushMessageType pushMessageType) {
        // Create a RestTemplate instance
        RestTemplate restTemplate = new RestTemplate();

// Define the URL to send the request to
        if (pushServerUrl.endsWith("/")) {
            pushServerUrl.substring(0, pushServerUrl.length() - 1);
        }
        String url = pushServerUrl + pushMessageType.getUri();

// Define the JSON payload
        String jsonPayload = "";
        try {
            jsonPayload = objectMapper.writeValueAsString(sendMessage);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

// Create a HttpHeaders instance to add authentication information
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization", "Bearer tk_zvdb67fwj1hrjivkq3ga9z7u63av5");

// Create a MultiValueMap to add additional headers
//        MultiValueMap<String, String> additionalHeaders = new LinkedMultiValueMap<>();
//        additionalHeaders.add("X-Custom-Header", "Custom-Value");
//        headers.putAll(additionalHeaders);

// Send the POST request
        ResponseEntity<String> response = restTemplate.postForEntity(url, jsonPayload, String.class, headers);

// Check the response status code
        NtfyReceiveMessage ntfyReceiveMessage = null;
        if (response.getStatusCode().is2xxSuccessful()) {
            // Process the response body (JSON)
            String responseBody = response.getBody();

            try {
                ntfyReceiveMessage = objectMapper.readValue(responseBody, NtfyReceiveMessage.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            // ...
        } else {
            // Handle the error response
            // ...

            log.error("Error sending message: {} with code: {}", response.getStatusCode(), jsonPayload);
        }


        return ntfyReceiveMessage;
    }
}
