package ru.yandex.direct.web.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import ru.yandex.direct.common.db.PpcPropertiesSupport;
import ru.yandex.direct.core.configuration.CoreConfiguration;
import ru.yandex.direct.core.entity.campaign.repository.CampaignRepository;
import ru.yandex.direct.dbutil.sharding.ShardHelper;
import ru.yandex.direct.dbutil.wrapper.DatabaseWrapperProvider;
import ru.yandex.direct.useractionlog.TableNames;
import ru.yandex.direct.useractionlog.db.ReadActionLogTable;
import ru.yandex.direct.useractionlog.db.ReadDictTable;
import ru.yandex.direct.useractionlog.db.ReadPpclogApiTable;
import ru.yandex.direct.useractionlog.db.ShardReplicaChooser;
import ru.yandex.direct.useractionlog.dict.DictDefaults;
import ru.yandex.direct.useractionlog.dict.DictRepository;
import ru.yandex.direct.useractionlog.reader.FilterLogRecordsByCampaignTypeBuilder;
import ru.yandex.direct.useractionlog.reader.UserActionLogReader;

@Configuration
@ComponentScan(
        basePackages = {
                "ru.yandex.direct.web.entity.useractionlog",
                "ru.yandex.direct.useractionlog.reader",
                "ru.yandex.direct.communication.config"
        }
)
@Import({
        CoreConfiguration.class,
        GraphqlConfiguration.class
})
public class UserActionLogConfiguration {

    @Bean
    public UserActionLogReader userActionLogReader(
            ShardReplicaChooser userActionLogShardReplicaChooser,
            DatabaseWrapperProvider databaseWrapperProvider) {
        return new UserActionLogReader(
                new ReadActionLogTable(userActionLogShardReplicaChooser::getForReading,
                        TableNames.READ_USER_ACTION_LOG_TABLE),
                new ReadPpclogApiTable(databaseWrapperProvider::get, TableNames.READ_PPCLOG_API_TABLE));
    }

    @Bean(name = "readOnlyDictRepository")
    public DictRepository readOnlyDictRepository(ShardReplicaChooser userActionLogShardReplicaChooser) {
        return DictDefaults.makeReadOnlyJournalDictRepository(
                new ReadDictTable(userActionLogShardReplicaChooser::getForReading,
                        TableNames.DICT_TABLE),
                userActionLogShardReplicaChooser);
    }

    @Bean(name = "filterLogRecordsByCampaignTypeBuilder")
    public FilterLogRecordsByCampaignTypeBuilder filterLogRecordsByCampaignTypeBuilder(
            CampaignRepository campaignRepository,
            ShardHelper shardHelper,
            PpcPropertiesSupport ppcPropertiesSupport) {
        return new FilterLogRecordsByCampaignTypeBuilder(campaignRepository, shardHelper, ppcPropertiesSupport);
    }
}
