package com.aip.gateway.api.repository;

import com.aip.gateway.api.dto.LinkedApiKeyDto;
import com.aip.gateway.api.dto.LinkedDecryptKeyDto;
import com.aip.gateway.api.model.app.AipSettings;
import com.aip.gateway.api.aip.utils.AipFileUtils;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Getter
@Setter
@Component
@RequiredArgsConstructor
public class AppRepository {

    private AipSettings settings = new AipSettings();
    private ConcurrentHashMap<String, String> supportedFileExtMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, String> protectedFileExtMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, String> supportedDelFileExtMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, String> protectedDelFileExtMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, LinkedApiKeyDto> apiKeyMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, LinkedDecryptKeyDto> decryptKeyMap = new ConcurrentHashMap<>();

    public int checkApiKeyValidation(String apiKey, String ipAddr) {
        LinkedApiKeyDto key = this.apiKeyMap.get(apiKey);
        if (key == null) {
            return 1;   // 등록되어 있지 않은 API KEY 입니다.
        }
        LinkedApiKeyDto server = key.getServerMap().get(ipAddr);
        if (server == null) {
            return 2;   // 등록되어 있지 않은 IP Address 에서 호출된 API KEY 입니다.
        }

        LocalDateTime curr = LocalDateTime.now();
        if (curr.isAfter(server.getExpiredAt())) {
            return 3; // API KEY 유효기간이 지났습니다.
        }
        return 0;   // KEY OK
    }

    public String getSupportedFileType(String fileName) {
        String fileExt = AipFileUtils.getExtension(fileName);
        return supportedFileExtMap.get(fileExt);
    }
}
