from src.logging.get_logger import get_logger
from src.model.db.wholesaler_master import WholesalerMasterModel
from src.repositories.base_repository import BaseRepository

logger = get_logger('卸データ取得')


class WholesalerMasterRepository(BaseRepository):

    FETCH_SQL = """\
    SELECT DISTINCT
        b.rec_whs_cd,
        b.rec_whs_sub_cd,
        v2.name,
        b.whs_name
    FROM src05.bio_sales b
    LEFT OUTER JOIN
    (
        SELECT
            sub_num,
            name,
            v_whs_cd,
            rec_sts_kbn
        FROM src05.whs_mst_v
        WHERE (SELECT STR_TO_DATE(syor_date, '%Y%m%d') FROM src05.hdke_tbl) BETWEEN start_date AND end_date
    )  v2
    ON b.v_whs_cd = v2.v_whs_cd
    AND v2.rec_sts_kbn <> '9'
    ORDER BY b.rec_whs_cd, b.rec_whs_sub_cd , b.whs_name DESC
    """

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