from src.logging.get_logger import get_logger
from src.model.db.inst_div_master import InstDivMasterModel
from src.repositories.base_repository import BaseRepository

logger = get_logger('COM_施設区分取得')


class InstDivMasterRepository(BaseRepository):

    FETCH_SQL = """\
        SELECT
            DISTINCT com_inst_div.inst_div_cd AS inst_div_cd,
            com_inst_div.inst_div_name AS inst_div_name
        FROM src05.com_inst
        JOIN src05.com_inst_div on com_inst.inst_div_cd = com_inst_div.inst_div_cd
        ORDER BY com_inst_div.inst_div_cd
    """

    def fetch_all(self) -> list[InstDivMasterModel]:
        try:
            self._database.connect()
            result = self._database.execute_select(self.FETCH_SQL)
            result_data = [res for res in result]
            models = [InstDivMasterModel(**r) for r in result_data]
            return models
        except Exception as e:
            logger.exception(f"DB Error : Exception={e.args}")
            raise e
        finally:
            self._database.disconnect()
