const axios       = require('axios');
const crypto      = require('crypto');
const dbConnect   = require('../../configs/dbConnection.js');

function getCurrentTimestamp() {
  const pad = n => n.toString().padStart(2, '0');
  const d = new Date();
  const YYYY = d.getFullYear();
  const MM   = pad(d.getMonth() + 1);
  const DD   = pad(d.getDate());
  const hh   = pad(d.getHours());
  const mm   = pad(d.getMinutes());
  const ss   = pad(d.getSeconds());
  return `${YYYY}-${MM}-${DD} ${hh}:${mm}:${ss}`;
}

const verifySignature = async (razorpay_order_id, razorpay_payment_id, razorpay_signature, orderId) => {

  console.log("1");
  console.log('rs',razorpay_signature);

  try {
    const generatedSignature = crypto
      .createHmac('sha256', '0mWsjR5ffOGHE4J2tiRKt1hy')
      .update(`${orderId}|${razorpay_payment_id}`)
      .digest('hex');
      
    console.log('gs' , generatedSignature)
    console.log("2");
    
    if (generatedSignature !== razorpay_signature) {
         //payment failure
      //return { success: false, message: 'Invalid signature, Payment failed.' };
      
        await dbConnect.query(
            "UPDATE onlinepay SET status = ? WHERE ipgid = ?",
            ["Transaction Failed", orderId]
            );
      return "failed";
    } else {
      //payment successful
      //return { success: true, message: 'Payment Successful.' };
       await dbConnect.query(
      "UPDATE onlinepay SET status = ? WHERE ipgid = ?",
      ["Transaction Successful", orderId]
    );
        return "success";

    }} catch (err) {
    console.error('razorPay signature verification error:', err);
    return { success: false, message: err.message };
  }
};

module.exports = {verifySignature};



