from src.logging.get_logger import get_logger
from src.model.db.ultmarc_trt_course import UltmarcDrTrtCourseDBModel
from src.repositories.base_repository import BaseRepository

logger = get_logger('COM_医師診療科目取得')


class UltmarcDrTrtCourseRepository(BaseRepository):

    FETCH_SQL = """\
        SELECT trt_course_name
        FROM src05.com_dr
        LEFT JOIN src05.com_dr_trt_course ON com_dr.dcf_pcf_dr_cd = com_dr_trt_course.dcf_pcf_dr_cd
        LEFT JOIN src05.com_trt_course ON com_dr_trt_course.trt_course_cd = com_trt_course.trt_course_cd
        WHERE com_dr.dcf_pcf_dr_cd = :id
        ORDER BY com_trt_course.trt_course_cd
    """

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

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