from src.repositories.base_repository import BaseRepository
from src.model.db.master_mente_count import MasterMenteCountModel
from src.logging.get_logger import get_logger

logger = get_logger('汎用区分マスタ')

class GenericKbnMstRepository(BaseRepository):
    
    FETCH_SQL = """\
    SELECT
        COUNT(*) AS count
    FROM
        src05.generic_kbn_mst
    WHERE
        generic_kbn_mst.generic_kbn_cd = :generic_kbn_cd
    AND 
        generic_kbn_mst.kbn_cd = :kbn_cd
    AND 
        STR_TO_DATE( :start_date , '%Y%m%d') BETWEEN generic_kbn_mst.start_date AND generic_kbn_mst.end_date\
    """


    def fetch_count(self, generic_kbn_cd: str, kbn_cd: str, start_date: str) -> MasterMenteCountModel:
        try: 
            query = self.FETCH_SQL
            result = self._database.execute_select(query, {'generic_kbn_cd': generic_kbn_cd, 'kbn_cd': kbn_cd, 'start_date' : start_date})
            models = [MasterMenteCountModel(**r) for r in result]
            if len(models) == 0:
                return 0
            return models[0].count
        except Exception as e:
            logger.error(f"DB Error : Exception={e.args}")
            raise e