package at.procon.eventhub.api;

import at.procon.eventhub.dto.EventHubEventDto;
import at.procon.eventhub.dto.EventHubPackageIngestRequest;
import at.procon.eventhub.dto.source.TelematicsPositionDto;
import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;
import org.apache.camel.ProducerTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/eventhub/acquisition")
public class EventHubIngestionController {

    private final ProducerTemplate producerTemplate;

    public EventHubIngestionController(ProducerTemplate producerTemplate) {
        this.producerTemplate = producerTemplate;
    }

    @PostMapping("/telematics/positions")
    public ResponseEntity<Map<String, Object>> ingestTelematicsPositions(@RequestBody List<TelematicsPositionDto> positions) {
        producerTemplate.sendBody("direct:telematics-position-input", positions);
        return accepted(positions.size(), "direct:telematics-position-input");
    }

    @PostMapping("/packages")
    public ResponseEntity<Map<String, Object>> ingestPackage(@Valid @RequestBody EventHubPackageIngestRequest request) {
        producerTemplate.sendBody("direct:eventhub-package-input", request);
        return accepted(request.events().size(), "direct:eventhub-package-input");
    }

    @PostMapping("/events")
    public ResponseEntity<Map<String, Object>> ingestNormalizedEvents(@RequestBody List<EventHubEventDto> events) {
        producerTemplate.sendBody("direct:eventhub-manual-input", events);
        return accepted(events.size(), "direct:eventhub-manual-input");
    }

    private ResponseEntity<Map<String, Object>> accepted(int count, String route) {
        return ResponseEntity.accepted().body(Map.of(
                "accepted", count,
                "route", route,
                "note", "Events are accepted into Camel acquisition routes, grouped by EventSource/package context, sorted in each batch, and then handed to the current ingestion adapter."
        ));
    }
}
