package gc.mda.kcg.domain.osint;

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;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api/osint")
@RequiredArgsConstructor
public class OsintController {

    private static final Set<String> VALID_REGIONS = Set.of("iran", "korea");

    private final CacheManager cacheManager;

    private final Map<String, Long> lastUpdated = new ConcurrentHashMap<>();

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

        if (!VALID_REGIONS.contains(region)) {
            return ResponseEntity.badRequest()
                    .body(Map.of("error", "유효하지 않은 region: " + region));
        }

        String cacheName = "iran".equals(region) ? CacheConfig.OSINT_IRAN : CacheConfig.OSINT_KOREA;
        List<OsintDto> items = getCachedItems(cacheName);
        long updatedAt = lastUpdated.getOrDefault(region, 0L);

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

    @SuppressWarnings("unchecked")
    private List<OsintDto> getCachedItems(String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache != null) {
            Cache.ValueWrapper wrapper = cache.get("data");
            if (wrapper != null) {
                return (List<OsintDto>) wrapper.get();
            }
        }
        return List.of();
    }

    public void markUpdated(String region) {
        lastUpdated.put(region, System.currentTimeMillis());
    }
}
