package com.arms.api.systeminfo.service;

import com.arms.api.systeminfo.model.SystemInfoVO;
import com.arms.api.systeminfo.model.SystemInfoFileName;
import com.arms.api.util.GiteaFileUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("systemInfo")
public class SystemInfoImpl implements SystemInfo {

    @Value("${spring.cloud.config.server.git.username}")
    private String gitUsername;
    @Value("${spring.cloud.config.server.git.password}")
    private String gitPassword;
    @Value("${spring.cloud.config.server.git.default-label}")
    private String gitBranch;
    @Value("${gitea.system-info}")
    private String directoryUrl;
    @Value("${filename.system-info.base}")
    private String systemInfoBaseName;


    @Override
    public SystemInfoVO getSystemInfo(Long orgLink) throws Exception {

        // org_link 를 통해
        // system-info_[org_link].yml 파일의 존재 유무를 확인.
        // 있으면 => 읽어서 보여주기
        // 없으면 => 베이스 파일 읽어서 반환
        List<String> yamlFiles = GiteaFileUtil.getYamlFilesFromDirectory(directoryUrl, gitBranch, gitUsername, gitPassword);

        Map<String, String> systemInfoFileNameUrlMap = new HashMap<>();
        for (String fileUrl : yamlFiles) {
            String ymlFileName = GiteaFileUtil.extractFileNameWithoutExtension(fileUrl);
            systemInfoFileNameUrlMap.put(ymlFileName, fileUrl);
        }

        String fileName = SystemInfoFileName.PREFIX.getNameType() + orgLink;
        if(systemInfoFileNameUrlMap.containsKey(fileName)) {
            return parseYamlFileToVO(systemInfoFileNameUrlMap.get(fileName), gitUsername, gitPassword);
        } else {
            String baseFileName = SystemInfoFileName.BASE.getNameType();
            return parseYamlFileToVO(systemInfoFileNameUrlMap.get(baseFileName), gitUsername, gitPassword);
        }
    }

    @SuppressWarnings("java:S2647")
    private static SystemInfoVO parseYamlFileToVO(String fileUrl, String username, String password) throws Exception {
        log.info("[ SystemInfoImpl :: parseYamlFileToVO ] :: fileUrl => {}", fileUrl);

        HttpURLConnection connection = (HttpURLConnection) new URL(fileUrl).openConnection();
        String auth = username + ":" + password;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        connection.setRequestProperty("Authorization", "Basic " + encodedAuth);

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Failed to download file: " + connection.getResponseMessage());
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

            return mapper.readValue(reader, SystemInfoVO.class);
        }
    }

}
