package com.arms.config;

import com.arms.api.admin.indexdata.annotation.MonthBackup;
import com.arms.api.admin.indexdata.annotation.MonthMerge;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class IndexBackupConfig {

    private static final String BASE_PACKAGE = "com.arms.api";

    private final ElasticsearchOperations operations;

    @Bean
    public List<String> monthBackupIndices() {
        List<String> indices = scanIndicesWithAnnotation(MonthBackup.class);
        log.info("[인덱스 스캔 완료] MonthBackup: {}", indices);
        return indices;
    }

    @Bean
    public List<String> monthMergeIndices() {
        List<String> indices = scanIndicesWithAnnotation(MonthMerge.class);
        log.info("[인덱스 스캔 완료] MonthMerge: {}", indices);
        return indices;
    }

    private List<String> scanIndicesWithAnnotation(Class<? extends java.lang.annotation.Annotation> annotationClass) {
        List<String> indices = new ArrayList<>();

        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(annotationClass));

        for (BeanDefinition bd : scanner.findCandidateComponents(BASE_PACKAGE)) {
            try {
                Class<?> clazz = Class.forName(bd.getBeanClassName());
                Document document = AnnotationUtils.findAnnotation(clazz, Document.class);
                if (document != null) {
                    IndexCoordinates indexCoordinates = operations.getIndexCoordinatesFor(clazz);
                    String indexName = indexCoordinates.getIndexName();
                    indices.add(indexName);
                }
            } catch (ClassNotFoundException e) {
                log.warn("클래스를 찾을 수 없습니다: {}", bd.getBeanClassName());
            }
        }

        return indices;
    }

}
