from src.logging.get_logger import get_logger
from src.model.db.ultmarc_inst_trt_course import UltmarcInstTrtCourseDBModel
from src.repositories.base_repository import BaseRepository

logger = get_logger('COM_施設診療科目取得')


class UltmarcInstTrtCourseRepository(BaseRepository):

    FETCH_SQL = """\
        SELECT trt_course_name_abb
        FROM src05.com_inst
        JOIN src05.com_inst_trt_course ON com_inst.dcf_dsf_inst_cd = com_inst_trt_course.dcf_dsf_inst_cd
        LEFT JOIN src05.com_trt_course ON com_inst_trt_course.trt_course_cd = com_trt_course.trt_course_cd
        WHERE com_inst.dcf_dsf_inst_cd = :id
        ORDER BY com_trt_course.trt_course_cd
    """

    def fetch_many(self, id) -> list[UltmarcInstTrtCourseDBModel]:
        try:
            self._database.connect()
            query = self.FETCH_SQL
            result = self._database.execute_select(query, {'id': id})

            models = [UltmarcInstTrtCourseDBModel(**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()
