from typing import List, Tuple

from maps_adv.stat_tasks_starter.lib.base import BaseClickhousePoint


class CampaignChargedStat(BaseClickhousePoint):
    SELECT_TEMPLATE = """
        SELECT CampaignID, SUM(Cost) AS charged
        FROM {database}.{charged_table}
        WHERE
            CampaignID IN ({campaigns_ids})
        GROUP BY CampaignID
    """

    def __init__(self, charged_table: str, **kwargs):
        self.database = kwargs["database"]
        self.charged_table = charged_table
        super().__init__(**kwargs)

    async def __call__(
        self, campaigns_ids: List[int]
    ) -> Tuple[Tuple[int, int, int, int]]:

        if not campaigns_ids:
            return ()

        full_sql = self.build_request(self.database, self.charged_table, campaigns_ids)

        return await self.client.execute(full_sql)

    @staticmethod
    def build_request(database: str, charged_table: str, campaigns_ids: List[int]):
        return CampaignChargedStat.SELECT_TEMPLATE.format(
            database=database,
            charged_table=charged_table,
            campaigns_ids=", ".join(map(str, campaigns_ids)),
        )
