from src.logging.get_logger import get_logger
from src.model.db.prefc_master import PrefcMasterModel
from src.repositories.base_repository import BaseRepository

logger = get_logger('都道府県マスタ取得')


class PrefcMasterRepository(BaseRepository):

    FETCH_SQL = """\
    SELECT DISTINCT
        com_inst.prefc_cd AS prefc_cd,
        mst_prefc.prefc_name AS prefc_name
    FROM
        src05.com_inst
    JOIN src05.mst_prefc ON com_inst.prefc_cd = mst_prefc.prefc_cd
    ORDER BY
        mst_prefc.prefc_cd
    """

    def fetch_all(self) -> list[PrefcMasterModel]:
        try:
            self._database.connect()
            result = self._database.execute_select(self.FETCH_SQL)
            result_data = [res for res in result]
            models = [PrefcMasterModel(**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()
