package com.ai.trackwalker.uavaccess.api;

import com.ai.trackwalker.uavaccess.common.AccessApiResponse;
import com.ai.trackwalker.uavaccess.common.Jsons;
import com.ai.trackwalker.uavaccess.config.UavAccessProperties;
import com.ai.trackwalker.uavaccess.event.VendorEventIngestService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/events/flighthub")
public class FlightHubEventController {
    private final UavAccessProperties properties;
    private final VendorEventIngestService events;

    public FlightHubEventController(UavAccessProperties properties, VendorEventIngestService events) {
        this.properties = properties;
        this.events = events;
    }

    @PostMapping
    public AccessApiResponse<?> ingest(
            @RequestHeader(name = "X-FlightHub-Event-Token", required = false) String token,
            @RequestHeader(name = "X-FlightHub-Event-Id", required = false) String eventId,
            @RequestHeader(name = "X-FlightHub-Event-Type", required = false) String eventType,
            @RequestHeader(name = "X-Connection-Id", defaultValue = "flighthub2-default") String connectionId,
            @RequestBody Map<String, Object> body
    ) {
        authorize(token);
        String resolvedId = firstNonBlank(
                eventId,
                text(body.get("event_id")),
                text(body.get("id")),
                UUID.randomUUID().toString()
        );
        String resolvedType = firstNonBlank(
                eventType,
                text(body.get("event_type")),
                text(body.get("type")),
                "unknown"
        );
        String eventTime = firstNonBlank(
                text(body.get("event_time")),
                text(body.get("occurred_at")),
                text(body.get("timestamp")),
                Instant.now().toString()
        );
        return AccessApiResponse.ok(events.ingest(
                connectionId,
                "EVENT_API",
                resolvedId,
                resolvedType,
                eventTime,
                body
        ));
    }

    private void authorize(String provided) {
        String expected = properties.getEventCallbackToken();
        if (expected == null || expected.isBlank()) {
            throw new ResponseStatusException(
                    HttpStatus.SERVICE_UNAVAILABLE,
                    "FLIGHTHUB_EVENT_CALLBACK_TOKEN must be configured"
            );
        }
        if (provided == null || !MessageDigest.isEqual(
                expected.getBytes(StandardCharsets.UTF_8),
                provided.getBytes(StandardCharsets.UTF_8)
        )) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid FlightHub event callback token");
        }
    }

    private String firstNonBlank(String... values) {
        for (String value : values) {
            if (value != null && !value.isBlank()) return value;
        }
        return "";
    }

    private String text(Object value) {
        return value == null ? "" : String.valueOf(value);
    }
}
