package com.eactive.eai.rms.ext.djb.common;

import com.eactive.eai.rms.data.entity.man.monitoringProperty.MonitoringProperty;
import com.eactive.eai.rms.data.entity.man.monitoringProperty.MonitoringPropertyId;
import com.eactive.eai.rms.data.entity.man.monitoringProperty.service.MonitoringPropertyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.Optional;

@Slf4j
public class DjbPropertyInjector {
    private final MonitoringPropertyService monitoringPropertyService;
    private final String groupId;


    public DjbPropertyInjector(MonitoringPropertyService monitoringPropertyService, String groupId) {
        this.monitoringPropertyService = monitoringPropertyService;
        this.groupId = groupId;
    }

    /**
     * DjbProperty의 URL 값들이 설정되어 있는지 확인
     * @param property 검사할 DjbProperty 객체
     * @return URL 값들이 모두 설정되어 있으면 true
     */
    public boolean isUrlConfigured(DjbProperty property) {
        if (property == null) return false;

        return StringUtils.isNotEmpty(property.getApiAllowIpList());
    }

    /**
     * URL 값이 비어있을 경우 DB에서 재로딩 시도
     * @param property 기존 DjbProperty 객체
     * @return 재로딩된 DjbProperty 객체 (재로딩 실패 시 기존 객체 반환)
     */
    public DjbProperty reloadIfUrlEmpty(DjbProperty property) {
        if (property == null) {
            return inject(new DjbProperty());
        }

        if (!isUrlConfigured(property)) {
            log.info("DjbProperty URL 값이 비어있어 DB에서 재로딩 시도");
            try {
                DjbProperty reloaded = inject(new DjbProperty());
                if (isUrlConfigured(reloaded)) {
                    log.info("DjbProperty 재로딩 성공");
                    return reloaded;
                } else {
                    log.warn("DjbProperty 재로딩 후에도 URL 값이 비어있음");
                }
            } catch (Exception e) {
                log.error("DjbProperty 재로딩 실패: {}", e.getMessage(), e);
            }
        }

        return property;
    }

    public <T> T inject(T property) {
        Class<?> clazz = property.getClass();

        for (Field field : clazz.getDeclaredFields()) {
            DjbPropertyValue anno = field.getAnnotation(DjbPropertyValue.class);

            if (anno != null) {
                String key = anno.key();

                // DB에 속성이 없으면 기본값으로 자동 생성
                ensurePropertyExists(groupId, key, anno.defaultValue());

                // 값 조회
                String rawValue = monitoringPropertyService.getPropertyValue(groupId, key, anno.defaultValue());
                Object convertedValue = convertValue(field.getType(), rawValue);

                field.setAccessible(true);
                try {
                    field.set(property, convertedValue);
                } catch (IllegalAccessException e) {
                    log.error("Failed to inject property: {} - {}", field.getName(), key, e);
                    throw new RuntimeException(e);
                }
            }
        }

        return property;
    }

    /**
     * 속성이 DB에 존재하는지 확인하고, 없으면 기본값으로 생성
     *
     * @param groupName 속성 그룹명
     * @param key 속성 키
     * @param defaultValue 기본값
     */
    private void ensurePropertyExists(String groupName, String key, String defaultValue) {
        MonitoringPropertyId id = new MonitoringPropertyId();
        id.setPrptyGroupName(groupName);
        id.setPrptyName(key);

        Optional<MonitoringProperty> existing = monitoringPropertyService.findById(id);

        if (!existing.isPresent()) {
            log.info("Property not found in DB, creating - Group: {}, Key: {}, DefaultValue: {}", groupName, key, defaultValue);

            MonitoringProperty property = new MonitoringProperty();
            property.setId(id);
            property.setPrpty2Val(defaultValue);

            monitoringPropertyService.save(property);
            log.info("Property created successfully - Group: {}, Key: {}", groupName, key);
        }
    }


    private static Object convertValue(Class<?> type, String rawValue) {
        if (rawValue == null) return null;
        if (StringUtils.isEmpty(rawValue)) return "";

        if (type == String.class) return rawValue;
        if (type == Integer.class || type == int.class) return Integer.valueOf(rawValue);
        if (type == Long.class || type == long.class) return Long.valueOf(rawValue);
        if (type == Double.class || type == double.class) return Double.valueOf(rawValue);
        if (type == Boolean.class || type == boolean.class) return Boolean.valueOf(rawValue);
        if (type == Float.class || type == float.class) return Float.valueOf(rawValue);
        if (type == Short.class || type == short.class) return Short.valueOf(rawValue);
        if (type == Byte.class || type == byte.class) return Byte.valueOf(rawValue);

        return rawValue;
    }
}
