import textwrap

from src.config.objects import LastFetchDatetime, TargetObject
from src.system_var.environments import FETCH_LIMIT_CLAUSE


class SOQLBuilder:
    def __init__(self, target_object: TargetObject, last_fetch_datetime: LastFetchDatetime) -> None:
        self.__SELECT_SOQL = textwrap.dedent("""\
            SELECT {column_or_expression} FROM {object_name}
            WHERE {datetime_column} > {last_fetch_datetime_from}
            AND {datetime_column} <= {last_fetch_datetime_to}
            {limit_clause}
        """)
        self.__target_object = target_object
        self.__last_fetch_datetime = last_fetch_datetime

    def create_count_soql(self):
        count_soql = self.__SELECT_SOQL.format(
            column_or_expression='COUNT(Id)',
            object_name=self.__target_object.object_name,
            last_fetch_datetime_from=self.__last_fetch_datetime.last_fetch_datetime_from,
            last_fetch_datetime_to=self.__last_fetch_datetime.last_fetch_datetime_to,
            datetime_column=self.__target_object.datetime_column,
            limit_clause=''
        )

        return count_soql

    def create_fetch_soql(self):
        columns = ','.join(self.__target_object.columns)
        fetch_soql = self.__SELECT_SOQL.format(
            column_or_expression=columns,
            object_name=self.__target_object.object_name,
            last_fetch_datetime_from=self.__last_fetch_datetime.last_fetch_datetime_from,
            last_fetch_datetime_to=self.__last_fetch_datetime.last_fetch_datetime_to,
            datetime_column=self.__target_object.datetime_column,
            limit_clause=FETCH_LIMIT_CLAUSE
        )

        return fetch_soql
