package com.lingniu.ingest.vehiclestate;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
@ConditionalOnProperty(prefix = "lingniu.ingest.vehicle-state", name = "enabled", havingValue = "true")
@ConditionalOnBean(VehicleStateRepository.class)
@RequestMapping(path = "/api/vehicle-state", produces = MediaType.APPLICATION_JSON_VALUE)
public final class VehicleStateController {

    private final VehicleStateRepository repository;

    public VehicleStateController(VehicleStateRepository repository) {
        if (repository == null) {
            throw new IllegalArgumentException("repository must not be null");
        }
        this.repository = repository;
    }

    @GetMapping("/{vin}")
    public ResponseEntity<String> state(@PathVariable String vin) {
        // 查询的是 Redis 最新状态快照，不是历史明细库。
        return json(repository.getState(vin));
    }

    @GetMapping("/{vin}/location")
    public ResponseEntity<String> location(@PathVariable String vin) {
        return json(repository.getLocation(vin));
    }

    @GetMapping("/{vin}/safety")
    public ResponseEntity<String> safety(@PathVariable String vin) {
        return json(repository.getSafety(vin));
    }

    @GetMapping("/{vin}/last-event")
    public ResponseEntity<String> lastEvent(@PathVariable String vin) {
        return json(repository.getLastEvent(vin));
    }

    private static ResponseEntity<String> json(Optional<String> value) {
        return value.map(json -> ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(json))
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}
