package ru.yandex.direct.web.entity.uac.service

import org.springframework.stereotype.Service
import ru.yandex.direct.core.entity.uac.model.TargetType
import ru.yandex.direct.dbutil.model.ClientId
import ru.yandex.direct.dbutil.sharding.ShardHelper
import ru.yandex.direct.grid.core.entity.showcondition.model.GdiAggregatedShowCondition
import ru.yandex.direct.grid.core.entity.showcondition.model.GdiAggregatedShowConditionFilter
import ru.yandex.direct.grid.core.entity.showcondition.model.GdiAggregatedShowConditionOrderBy
import ru.yandex.direct.grid.core.entity.showcondition.service.GridAggregatedShowConditionService
import ru.yandex.direct.utils.DateTimeUtils.fromEpochSeconds

@Service
class UacAggregatedShowConditionsService(
    private val gridAggregatedShowConditionService: GridAggregatedShowConditionService,
    private val shardHelper: ShardHelper
) {
    private companion object {
        val GOAL_IDS: Set<Long> = TargetType.values()
            .mapNotNull { it.goalId }
            .filter {it != 0L}
            .toSet()
    }

    fun getAggregatedShowConditions(
        operatorUid: Long,
        clientId: ClientId,
        campaignId: Long,
        fromSeconds: Long,
        toSeconds: Long,
        orderBy: GdiAggregatedShowConditionOrderBy?
    ): List<GdiAggregatedShowCondition> {

        return gridAggregatedShowConditionService.getShowConditions(
            shardHelper.getShardByCampaignId(campaignId),
            operatorUid,
            clientId,
            GdiAggregatedShowConditionFilter().withCampaignIdIn(setOf(campaignId)),
            orderBy?.let {it -> listOf(it)} ?: emptyList(),
            fromEpochSeconds(fromSeconds).toLocalDate(),
            fromEpochSeconds(toSeconds).toLocalDate(),
            GOAL_IDS
        )
    }
}
