const cors    = require('cors');
const axios   = require('axios');
const crypto = require('crypto')
const jwt     = require('jsonwebtoken');
const mysql = require("mysql2/promise");

exports.createRefundRequest = async (req, res) => {
    
//     const {
//     fare,
//     orderDate,
//     uid,
//     name,
//     ticketId,
//     paymentfor,
//     userIp,
    
//   } = req.body;

const mercid      = 'HYDBOBROS';
const clientid    = 'hydbobros';
const secretKey   = 'niHCVRKWasUbe2MWR41DI3xtG3dKLWgR';
const billdeskRefundURL = 'https://uat1.billdesk.com/u2/payments/ve1_2/refunds/create';;
const responseURL = 'http://api.bobros.in/';

const now = new Date();

  // toISOString gives format: 'YYYY-MM-DDTHH:mm:ss.sssZ'
  // We strip milliseconds and replace 'Z' with timezone offset
  const isoString = now.toISOString().split('.')[0]; // Remove milliseconds
  const timezoneOffsetMinutes = now.getTimezoneOffset();
  
  const offsetHours = String(Math.floor(Math.abs(timezoneOffsetMinutes) / 60)).padStart(2, '0');
  const offsetMinutes = String(Math.abs(timezoneOffsetMinutes) % 60).padStart(2, '0');
  const offsetSign = timezoneOffsetMinutes <= 0 ? '+' : '-';

  const timezone = `${offsetSign}${offsetHours}:${offsetMinutes}`;
  const atomDateTime = `${isoString}${timezone}`;


console.log(atomDateTime)

const currentTimestamp = Date.now(); // or any specific timestamp in milliseconds
const date = new Date(currentTimestamp);

const servertimeYYYYMMddHHmmss = 
    date.getFullYear().toString() +
    String(date.getMonth() + 1).padStart(2, '0') +
    String(date.getDate()).padStart(2, '0') +
    String(date.getHours()).padStart(2, '0') +
    String(date.getMinutes()).padStart(2, '0') +
    String(date.getSeconds()).padStart(2, '0');

console.log(servertimeYYYYMMddHHmmss);


    const refundPayload = {
        "transactionid": "TICKET456",
        "orderid": "OAAW1T7HQYIIQZLZ",
        "mercid" : "HYDBOBROS",
        "transaction_date":"2025-05-16T10:15:30+05:30",
        "txn_amount" : "500.00",
        "refund_amount":"300.00",
        "currency": "356",
        "merc_refund_rf_no": "Refund1"

    };
    
    // Sign with HS256 HMAC
    const jwsHeader = { alg: 'HS256', clientid, kid: "HMAC"};

    // const encodedPayload = jwt.sign(payload, secretKey, options )
    
    const encodedPayload  = jwt.sign(refundPayload, secretKey, {
      algorithm: 'HS256',
      header: jwsHeader,
    });
   
   
    function generateSignature(payload, secretKey) {
  return crypto.createHmac('sha256', secretKey).update(payload).digest('base64');
}

     
     const payloadString = JSON.stringify(refundPayload);
  const signature = generateSignature(payloadString, secretKey);
    
    const headers = {
        'Content-Type': 'application/json',
        'BD-Traceid' : 'BCZN1UBMLCNXM744',
        'X-VERIFY-SIGNATURE': signature,
        'BD-Timestamp': servertimeYYYYMMddHHmmss,
        'Accept'      : 'application/jose',
      };

try {

    const resp = await axios.post(billdeskRefundURL, encodedPayload, { headers });
    console.log("resp", resp);

    const decodedResp = jwt.verify(resp.data, secretKey, { algorithms: ['HS256'] });
    console.log("decodedResp", decodedResp);
    res.json({
  originalResponse: resp.data // or just `resp` if you want everything, but usually `resp.data` is enough
});
    // res.status(200).send(decoded);
  }
  catch (error) {
    // Distinguish HTTP errors from signature errors
    // if (err.response) {
      // BillDesk returned a non‑2xx status: forward their payload & status
    //  const decodedResp = jwt.verify(err.response.data, secretKey, { algorithms: ['HS256'] });
    console.log("decodedResp", error.response);
    //   return res.status(err.response.status).send(err.response);
    res.json({
    message: 'Refund failed',
    error: {
      status: error.response?.status,
      data: error.response?.data,
      message: error.message,
    }
  });
    // }
    // Signature verification or other server error
    // next(new Error('Invalid response signature or server error'));
  }
};

    // const payloadString = JSON.stringify(refundPayload);
    // const signature =  jwt.sign(payloadString, secretKey);
    
//     try {
      
//     const resp = await axios.post(billdeskRefundURL, encodedPayload, { headers });
//     console.log('Refund response:', response.data);
//     res.status(200).send(response.data);
//   } catch (error) {
//     console.error('Refund request failed:', error.response ? error.response.data : error.message);
//     res.status(400).json({
//     message: 'Refund request failed',
//     error: error.response ? error.response.data : error.message
//   });  }
// }

    
//     // Sign with HS256 HMAC
//     const jwsHeader = { alg: 'HS256', clientid, kid: "HMAC"};

//     // const encodedPayload = jwt.sign(payload, secretKey, options )
    
//     const encodedPayload  = jwt.sign(payload, secretKey, {
//       algorithm: 'HS256',
//       header: jwsHeader,
//     });

//     console.log("encodedPayload:", encodedPayload)
 
//     const headers = {
//       'Content-Type': 'application/jose',
//       'Accept'      : 'application/jose',
//     //   'BD-Traceid':   ticketId,
//       'BD-Timestamp': servertimeYYYYMMddHHmmss
//     };
//     console.log("headers", headers);


//   try {

//     const resp = await axios.post(billdeskRefundURL, encodedPayload, { headers });
//     console.log("resp", resp);

//     const decodedResp = jwt.verify(resp.data, secretKey, { algorithms: ['HS256'] });
//     console.log("decodedResp", decodedResp);
//     res.json({
//   decodedData: {
//     merchantOrderId: decodedResp.orderid,
//     bdOrderId:       decodedResp.bdorderid,
//     authToken:       decodedResp.authToken
//   },
//   originalResponse: resp.data // or just `resp` if you want everything, but usually `resp.data` is enough
// });
//     // res.status(200).send(decoded);
//   }
//   catch (err) {
//     // Distinguish HTTP errors from signature errors
//     if (err.response) {
//       // BillDesk returned a non‑2xx status: forward their payload & status
//      const decodedResp = jwt.verify(err.response.data, secretKey, { algorithms: ['HS256'] });
//     console.log("decodedResp", decodedResp);
//       return res.status(err.response.status).send(decodedResp);
//     }
//     // Signature verification or other server error
//     next(new Error('Invalid response signature or server error'));
//   }
// };