// const axiosPaystack = require('../helpers/paystack-axios-instance-and-interceptor.helper')
// const paystackKey = require('../helpers/paystack-key.helper')()
const paymentHistory = require("../../models").payment_history;
const User = require("../../models").users
var crypto = require('crypto');
const Subcriptions = require("../../models").subscriptions
const BindingPayment = require("../../models").binding_payments;
const Packages = require("../../models").packages;
const axios = require('axios');
const ODFORMS = require("../../models").odfel_forms;

async function recordPaymentToSchoolPortal(payload) {
    try {
      const apiUrl = 'https://portal.kwarastatepolytechnic.edu.ng/api/pday.php';
  
      await axios.post(apiUrl, payload);
    } catch (error) {
      console.error('Error:', error.response ? error.response.data : error.message);
    }
  }
exports.webhook = async (req, res) => {
    try {
        const PaystackDetails = require("../../models").paystack_details
        const paystackKey = await PaystackDetails.findAll()
        var secret = paystackKey[0].LIVE_SECRET_KEY; 
        var secret2 = paystackKey[0].TEST_SECRET_KEY; 
        const RequestIp = require('@supercharge/request-ip')
        const ip = RequestIp.getClientIp(req)
        const validIps = ['52.31.139.75', '52.49.173.169','52.214.14.220']
        var event = req.body
        

        const hash = crypto.createHmac('sha512',event.data.metadata.is_odfel == true ? secret2 : secret ).update(JSON.stringify(event)).digest('hex');
        if (hash == req.headers['x-paystack-signature'] && validIps.includes(ip)) {

            if(event.data.metadata.is_odfel == true && event.data.status === "success"){
                await ODFORMS.update({txn_status:"success"},{where: { id:event.data.metadata.transaction_id } , raw:true});
                return res.status(200).send()
            }

            if(event.data.metadata.paymentType){
                const verifyPaymentHistory = BindingPayment.findOne({
                    where: {
                        txn_ref: event.data.reference,
                        user_id: event.data.metadata.user_id
                    }
                })

                if (!verifyPaymentHistory) {
                    return res.send(404)
                }

                const updatePayment = {
                    paystack_event: event.event,
                    txn_desc: event.data.message,
                    txn_status: event.data.status,
                    txn_channel: event.data.channel,
                }
    
                await BindingPayment.update(updatePayment, {
                    where: {
                        txn_ref: event.data.reference,
                        user_id: event.data.metadata.user_id
                    }
                })
                const user = await User.findOne({
                  where: { id: event.data.metadata.user_id },
                  raw:true
                });
                if (event.data.status === "success") {
                    const updateUser = {
                        status: "PAID"
                    }
                    await BindingPayment.update(updateUser, {
                        where: {
                            user_id: event.data.metadata.user_id
                        }
                    })
                }
                    recordPaymentToSchoolPortal({
                      amount: parseInt(verifyPaymentHistory.amount),
                      username: user.username,
                      payment_type: "Project Binding",
                    });
                    res.status(200).send();
            }else{
                const verifyPaymentHistory = await paymentHistory.findOne({
                    where: {
                        txn_ref: event.data.reference,
                        username: event.data.metadata.matricNumber
                    },
                    raw:true
                })
    
                const findUser = await User.findOne({
                    where: {
                        username: event.data.metadata.matricNumber
                    }
                })
    
                if (!verifyPaymentHistory) {
                    return res.send(404)
                }
    
    
                const updatePayment = {
                    paystack_event: event.event,
                    txn_desc: event.data.message,
                    txn_status: event.data.status,
                    txn_channel: event.data.channel,
                }
    
                await paymentHistory.update(updatePayment, {
                    where: {
                        txn_ref: event.data.reference,
                        username: event.data.metadata.matricNumber
                    }
                })
               const packageDetail = await Packages.findOne({
                    where: {
                        id:verifyPaymentHistory.package_id
                    }, 
                    raw:true
                })
    
                if (event.data.status === "success") {
                    const updateUser = {
                        payment_status: "PAID",
                        active:true
                    }
                    const updatePaid = await User.update(updateUser, {
                        where: {
                            username: event.data.metadata.matricNumber
                        }
                    })
    
                  const createSub =  await Subcriptions.create({
                    user_id: findUser.id,
                    payment_id: event.data.reference,
                    pakage_id: 	verifyPaymentHistory.package_id
                    })
    
                    if (updatePaid && createSub){
                        recordPaymentToSchoolPortal({
                          amount: parseInt(verifyPaymentHistory.amount),
                          username: event.data.metadata.matricNumber,
                          payment_type: packageDetail.name,
                        });
                        res.status(200).send();
                    }
                       
                }
            }
            
        }else{
            res.status(401).send();
        }
    } catch (e) {
        console.log(e)
        // const updatePayment = {
        //     txn_status: "Failed",
        // }

        // await paymentHistory.update(updatePayment, {
        //     where: {
        //         txn_ref: event.data.reference,
        //         username: event.data.metadata.matricNumber
        //     }
        // })
        res.status(500).send();
    }
}