package com.mvrent.carrental.service;

import com.mvrent.carrental.model.VehicleLocation;
import com.mvrent.carrental.repository.VehicleLocationRepository;
import com.mvrent.carrental.web.TelematicsPing;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class TelematicsService {

    private final VehicleLocationRepository locationRepository;
    private final CarService carService;

    @Value("${app.telematics.api-key:}")
    private String apiKey;

    public boolean apiKeyValid(String provided) {
        // When no key is configured, accept everything (dev convenience).
        return apiKey == null || apiKey.isBlank() || apiKey.equals(provided);
    }

    public List<VehicleLocation> findAll() {
        return locationRepository.findAll();
    }

    /** Upsert the latest position for a car. */
    @Transactional
    public VehicleLocation ingest(TelematicsPing p) {
        if (p.carId() == null) throw new IllegalArgumentException("carId is required");
        if (p.lat() == null || p.lng() == null) throw new IllegalArgumentException("lat and lng are required");

        VehicleLocation loc = locationRepository.findByCarId(p.carId())
                .orElseGet(() -> VehicleLocation.builder().car(carService.findById(p.carId())).build());
        loc.setLatitude(p.lat());
        loc.setLongitude(p.lng());
        loc.setSpeedKph(p.speed());
        loc.setHeading(p.heading());
        if (p.odometer() != null) loc.setOdometer(p.odometer());
        loc.setIgnitionOn(p.ignition());
        loc.setUpdatedAt(LocalDateTime.now());
        return locationRepository.save(loc);
    }
}
