from logging_config import get_logger

logger = get_logger(__name__)

class Repository:

    def __init__(self, db):
        self.db = db

    def get_records(self, dccb):
        logger.info("Fetching records for DCCB=%s", dccb)

        return self.db.fetch_all("""
        SELECT TXN_NO,TXN_DATE,DCCB_CODE,BR_CODE,SRC_AC_NO,DEST_AC_NO,
               IFSC_CODE,TXN_AMT,BENEFICIARY_NAME,
               BENEFICIARY_ADD,REMITTER_NAME,CBS_QUEUE_NO2
        FROM NEFT_RTGS_TXN_QUEUE
        WHERE DCCB_CODE = :d
        AND TRUNC(TXN_DATE)=TRUNC(SYSDATE)
        """, {"d": dccb})

    def exists_by_ref(self, ref):
        logger.debug("Checking duplicate REF=%s", ref)

        res = self.db.fetch_all(
            "SELECT 1 FROM outward_neft_api_log WHERE REF_NO=:r",
            {"r": ref}
        )

        return len(res) > 0

    def insert_outward_log(self, d):
        logger.debug("Insert data: %s", d)

        self.db.execute("""
        INSERT INTO outward_neft_api_log(
        BANKCODE,TXNCODE,TXNIND,JRNL_ID,REF_NO,TRAN_DATE,
        TXN_AMT,RECVR_ACCT_NO,SENDER_ACCT_NO,
        RECIEVER_IFSC,SENDER_NAME,RECIEVER_NAME,
        BENEFICIARY_ADDRESS,SENDER_TO_RECIVER_INFO,MSG_TYPE
        )
        VALUES (
        :bankcode,'OUTWARD NEFT','DR',:jrnl_id,:ref_no,:tran_date,
        :txn_amt,:recv_ac,:send_ac,
        :ifsc,:sender_name,:receiver_name,
        :beneficiary_address,:sender_info,'N06')
        """, d)

    def call_proc(self):
        return self.db.call_procedure("neft_api_txn_post")