package io.github.js0ny.ilp_coursework.service;

import java.net.http.HttpClient;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.github.js0ny.ilp_coursework.data.common.DroneEvent;
import io.github.js0ny.ilp_coursework.data.response.DeliveryPathResponse;

@Service
public class TelemetryService {
    private final HttpClient client;
    private final ObjectMapper mapper;

    private final String BLACKBOX_URL;

    public TelemetryService() {
        this.client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();

        this.mapper = new ObjectMapper();
        this.BLACKBOX_URL = System.getenv().getOrDefault("BLACKBOX_ENDPOINT", "http://localhost:3000");
    }

    public void sendEventAsyncByPathResponse(DeliveryPathResponse resp) {
        var events = DroneEvent.fromPathResponse(resp);
        for (var event : events) {
            sendEventAsync(event);
        }
    }

    public void sendEventAsyncByPathResponse(DeliveryPathResponse resp, LocalDateTime baseTimestamp) {
        var events = DroneEvent.fromPathResponseWithTimestamp(resp, baseTimestamp);
        for (var event : events) {
            sendEventAsync(event);
        }
    }

    public void sendEventAsyncByPathResponse(DeliveryPathResponse resp,
            Map<Integer, LocalDateTime> deliveryTimestamps) {
        var events = DroneEvent.fromPathResponseWithTimestamps(resp, deliveryTimestamps);
        for (var event : events) {
            sendEventAsync(event);
        }
    }

    public void sendEventAsync(DroneEvent event) {
        CompletableFuture.runAsync(() -> {
            try {
                String json = mapper.writeValueAsString(event);
                System.out.println("[INFO] Sending telemetry event: " + json);
                var request = java.net.http.HttpRequest.newBuilder()
                        .uri(java.net.URI.create(BLACKBOX_URL + "/ingest"))
                        .header("Content-Type", "application/json")
                        .POST(java.net.http.HttpRequest.BodyPublishers.ofString(json))
                        .build();

                client.send(request, java.net.http.HttpResponse.BodyHandlers.ofString());
            } catch (Exception e) {
                System.err.println("[ERROR] Failed to send telemetry event: " + e.getMessage());
            }
        });

    }

}
