package com.dbnt.kcscbackend.admin.standards.service;

import com.dbnt.kcscbackend.admin.standards.entity.TnApiKey;
import com.dbnt.kcscbackend.admin.standards.repository.ApiKeyRepository;
import lombok.RequiredArgsConstructor;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@RequiredArgsConstructor
public class AdminApiService extends EgovAbstractServiceImpl {
    private final ApiKeyRepository apiKeyRepository;

    public Map<String, Object> selectApiList() {
        Map<String, Object> resultMap = new HashMap<>();

        long totalRecordCount = apiKeyRepository.count();                       // 전체 레코드 수 가져오기
        List<TnApiKey> apiList = apiKeyRepository.findAllByOrderByEndDtDesc();  // 개인 정보 로그 리스트 가져오기

        resultMap.put("resultCnt", String.valueOf(totalRecordCount));           // 개수를 resultMap에 추가
        resultMap.put("resultList", apiList);                                   // 결과를 resultMap에 추가

        return resultMap;
    }

    public TnApiKey getApiKeyById(String userId) { return apiKeyRepository.findById(userId).orElse(null); }

    @Transactional
    public String modifyApi(TnApiKey tnApiKey) {
        try {
            apiKeyRepository.save(tnApiKey);
            return "API key updated successfully";
        } catch (Exception e) {
            return "Failed to update API key";
        }
    }

    public List<Object[]> selectApiDailyCount(String UserId) {
        return apiKeyRepository.selectCountApiDaily(UserId);
    }           // 일자별 API 요청횟수

}
