package com.arms.api.report.weekly.service;

import com.arms.api.report.weekly.model.vo.StateMappingInfo;
import com.arms.api.report.weekly.model.vo.StateMappingResponse;
import com.arms.api.serverinfo.msa_communicate.MiddleProxyArmsStateCategory;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@AllArgsConstructor
public class StateMappingCacheService {

    private final MiddleProxyArmsStateCategory middleProxyFeignService;

    private static StateMappingInfo cachedStateMappingInfo;

    @PostConstruct
    public void init() {
        try {
            cachedStateMappingInfo = fetchStateMappingInfo();
            log.info("[StateMappingCacheService :: init] :: StateMappingInfo loaded at startup.");
        } catch (Exception e) {
            log.warn("[StateMappingCacheService :: init] :: Failed to load StateMappingInfo at startup.", e);
        }
    }

    public StateMappingInfo getStateMappingInfo() {
        StateMappingInfo latest = fetchStateMappingInfo();
        if (latest != null) {
            cachedStateMappingInfo = latest;
        }
        return cachedStateMappingInfo;
    }

    private StateMappingInfo fetchStateMappingInfo() {
        StateMappingResponse response = middleProxyFeignService.getStateMappingInfo().getResponse();
        if (response == null) {
            log.info("[StateMappingCacheService :: fetchStateMappingInfo] :: StateMappingResponse is null.");
            return null;
        }
        return response.toStateMappingInfo();
    }
}