package com.lingniu.ingest.vehiclestat;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.Map;

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

    private final VehicleStatRepository repository;

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

    @GetMapping("/{vin}/daily")
    public ResponseEntity<Map<String, Object>> daily(
            @PathVariable String vin,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        return repository.findDailyStat(vin, date)
                .map(stat -> ResponseEntity.ok(toJson(stat)))
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    private static Map<String, Object> toJson(VehicleDailyStatResult stat) {
        Map<String, Object> json = new LinkedHashMap<>();
        json.put("vin", stat.vin());
        json.put("statDate", stat.statDate().toString());
        json.put("dailyMileageKm", stat.dailyMileageKm().isPresent()
                ? stat.dailyMileageKm().getAsDouble()
                : null);
        json.put("dailyMileageStrategy", stat.dailyMileageStrategy().name());
        return json;
    }
}
