from src.logging.get_logger import get_logger
from src.model.db.pharmacy_product_master import PharmacyProductMasterModel
from src.repositories.base_repository import BaseRepository

logger = get_logger('製品取得')


class PharmacyProductMasterRepository(BaseRepository):

    FETCH_SQL = """\
    SELECT
        CONCAT(IFNULL(t1.mkr_cd, ''), ' ', IFNULL(t1.mkr_inf_1, '')) AS mkr_cd_name
    FROM
        src05.phm_prd_mst_v t1
    INNER JOIN
    (
        SELECT
            prd_cd, MAX(sub_num) AS sno
        FROM
            src05.phm_prd_mst_v
        WHERE rec_sts_kbn <> '9'
        GROUP BY prd_cd
    ) fmv2
    ON t1.prd_cd = fmv2.prd_cd AND t1.sub_num = fmv2.sno
    WHERE
        t1.mkr_cd IS NOT NULL
    ORDER BY mkr_cd
    """

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