// const mysql = require("mysql2/promise");
const dbConnect = require('../configs/dbConnection');
const { retrieveTransaction }  = require('../../BilldeskPG/services/retrieveTransaction.js')
require("dotenv").config();

async function processTransactions() {
  

  try {
       console.log(`cron job`);
        const [rows] = await dbConnect.query(
      `

    SELECT *
    FROM onlinepay
    WHERE ipgid LIKE 'BDPG%'
    AND status NOT IN ('Transaction Successful', 'Transaction Failed')
    AND created_at BETWEEN NOW() - INTERVAL 20 MINUTE
    AND NOW() - INTERVAL 10 MINUTE;
      `
    );

    console.log(`Found ${rows.length} initiated transactions`);
    const mercid = process.env.BD_MERCHANT_ID;

    for (const row of rows) {
      const orderId = row.ipgid;
      console.log(orderId);

      try {
        const response = await retrieveTransaction({orderid: orderId});


        // Optional DB update, 
        // await connection.execute(
        //     UPDATE onlinepay
        //   SET status = ?, updated_at = NOW()
        //   WHERE order_id = ?
        //   `,
        //   [apiResponse.status.toLowerCase(), orderId]
        // );

      } catch (apiError) {
        console.error(`API error for orderId ${orderId}:`, apiError.message);
      }
    }

  } catch (dbError) {
    console.error("Database error:", dbError.message);
  } 
}

module.exports = {processTransactions};
