package com.mvrent.carrental.controller;

import com.mvrent.carrental.service.TelematicsService;
import com.mvrent.carrental.web.TelematicsPing;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Device-facing ingest endpoint for GPS pings. Authenticated by an API key
 * header ({@code X-API-KEY}) rather than a session, so trackers can post directly.
 */
@RestController
@RequestMapping("/api/telematics")
@RequiredArgsConstructor
public class TelematicsApiController {

    private final TelematicsService telematicsService;

    @PostMapping("/ingest")
    public ResponseEntity<?> ingest(@RequestHeader(value = "X-API-KEY", required = false) String apiKey,
                                    @RequestBody TelematicsPing ping) {
        if (!telematicsService.apiKeyValid(apiKey)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("ok", false, "message", "Invalid API key"));
        }
        try {
            telematicsService.ingest(ping);
            return ResponseEntity.ok(Map.of("ok", true));
        } catch (IllegalArgumentException ex) {
            return ResponseEntity.badRequest().body(Map.of("ok", false, "message", ex.getMessage()));
        }
    }
}
