package com.arms.egovframework.javaservice.esframework.config;

import com.arms.egovframework.javaservice.esframework.model.entity.BaseEntity;
import com.arms.egovframework.javaservice.esframework.repository.common.EsCommonRepository;
import com.arms.egovframework.javaservice.esframework.repository.common.EsCommonRepositoryImpl;
import com.arms.egovframework.javaservice.esframework.repository.common.EsCommonRepositoryWrapper;
import org.opensearch.data.core.OpenSearchOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.repository.support.MappingElasticsearchEntityInformation;

public abstract class EsRepositoryWrapperConfig {

    @Autowired
    private ElasticsearchOperations operations;

    @Autowired
    private ElasticsearchConverter converter;

    @SuppressWarnings("unchecked")
    protected <T extends BaseEntity> EsCommonRepositoryWrapper<T> repositoryOf(Class<T> entityClass) {
        ElasticsearchPersistentEntity<T> pe = (ElasticsearchPersistentEntity<T>)
                converter.getMappingContext().getRequiredPersistentEntity(entityClass);
        EsCommonRepository<T, ?> repo = new EsCommonRepositoryImpl<>(
                new MappingElasticsearchEntityInformation<>(pe), (OpenSearchOperations) operations);
        return new EsCommonRepositoryWrapper<>(repo, entityClass);
    }
}
