package com.lingniu.ingest.vehiclestate;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Optional;

public final class RedisVehicleStateRepository implements VehicleStateRepository {

    private final StringRedisTemplate redis;

    public RedisVehicleStateRepository(StringRedisTemplate redis) {
        if (redis == null) {
            throw new IllegalArgumentException("redis must not be null");
        }
        this.redis = redis;
    }

    @Override
    public void putState(String vin, String json) {
        // 每辆车一个 Redis key，读最新状态时不需要扫描或 join 历史表。
        put(key("vehicle:state:", vin), json);
    }

    @Override
    public void putLocation(String vin, String json) {
        put(key("vehicle:location:", vin), json);
    }

    @Override
    public void putSafety(String vin, String json) {
        put(key("vehicle:safety:", vin), json);
    }

    @Override
    public void putLastEvent(String vin, String json) {
        put(key("vehicle:event:last:", vin), json);
    }

    @Override
    public Optional<String> getState(String vin) {
        return get(key("vehicle:state:", vin));
    }

    @Override
    public Optional<String> getLocation(String vin) {
        return get(key("vehicle:location:", vin));
    }

    @Override
    public Optional<String> getSafety(String vin) {
        return get(key("vehicle:safety:", vin));
    }

    @Override
    public Optional<String> getLastEvent(String vin) {
        return get(key("vehicle:event:last:", vin));
    }

    private void put(String key, String json) {
        redis.opsForValue().set(key, json == null ? "{}" : json);
    }

    private Optional<String> get(String key) {
        return Optional.ofNullable(redis.opsForValue().get(key));
    }

    private static String key(String prefix, String vin) {
        if (vin == null || vin.isBlank()) {
            throw new IllegalArgumentException("vin must not be blank");
        }
        return prefix + vin;
    }
}
