package gc.mda.kcg.domain.satellite;

import gc.mda.kcg.collector.satellite.SatelliteCollector;
import gc.mda.kcg.config.CacheConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/satellites")
@RequiredArgsConstructor
public class SatelliteController {

    private final CacheManager cacheManager;
    private final SatelliteCollector satelliteCollector;

    @GetMapping
    public ResponseEntity<Map<String, Object>> getSatellites(
            @RequestParam(defaultValue = "iran") String region) {

        Cache cache = cacheManager.getCache(CacheConfig.SATELLITES);
        Cache.ValueWrapper wrapper = cache != null ? cache.get("data") : null;

        @SuppressWarnings("unchecked")
        List<SatelliteDto> sats = (wrapper != null && wrapper.get() instanceof List<?>)
                ? (List<SatelliteDto>) wrapper.get()
                : List.of();

        long lastUpdated = satelliteCollector.getLastUpdated();

        return ResponseEntity.ok(Map.of(
                "region", region,
                "count", sats.size(),
                "lastUpdated", lastUpdated,
                "satellites", sats
        ));
    }
}
