from src.logging.get_logger import get_logger
from src.model.db.ultmarc_doctor_wrkplace_his import \
    UltmarcDoctorWrkplaceHisDBModel
from src.repositories.base_repository import BaseRepository

logger = get_logger('COM_医師勤務先履歴取得')


class UltmarcDoctorWrkplaceHisRepository(BaseRepository):

    FETCH_SQL = """\
        SELECT
            com_inst.dcf_dsf_inst_cd,
            com_inst.inst_name_kanji,
            com_blng_sec.blng_sec_name,
            univ_post.form_post_name as univ_post_name,
            post.form_post_name as post_name,
            com_dr_wrkplace_his.aply_start_ymd,
            com_dr_wrkplace_his.aply_end_ymd
        FROM com_dr
        LEFT JOIN com_dr_wrkplace_his ON com_dr.dcf_pcf_dr_cd = com_dr_wrkplace_his.dcf_pcf_dr_cd
        LEFT JOIN com_inst ON com_dr_wrkplace_his.dcf_dsf_inst_cd = com_inst.dcf_dsf_inst_cd
        LEFT JOIN com_blng_sec ON com_dr_wrkplace_his.blng_sec_cd = com_blng_sec.blng_sec_cd
        LEFT JOIN com_post as univ_post ON com_dr_wrkplace_his.identity_cd = univ_post.post_cd
        LEFT JOIN com_post as post ON com_dr_wrkplace_his.post_cd = post.post_cd
        WHERE com_dr.dcf_pcf_dr_cd = :id
        ORDER BY com_dr_wrkplace_his.aply_end_ymd DESC,
            com_dr_wrkplace_his.aply_start_ymd DESC
    """

    def fetch_many(self, id) -> list[UltmarcDoctorWrkplaceHisDBModel]:
        try:
            self._database.connect()
            query = self.FETCH_SQL
            result = self._database.execute_select(query, {'id': id})
            models = [UltmarcDoctorWrkplaceHisDBModel(**r) for r in result]
            if len(models) == 0:
                return None
            return models
        except Exception as e:
            logger.exception(f"DB Error : Exception={e.args}")
            raise e
        finally:
            self._database.disconnect()
