// 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;

exports.webhook = async (req, res) => {
    try {
        const PaystackDetails = require("../../models").paystack_details
        const paystackKey = await PaystackDetails.findAll()
        var secret = paystackKey[0].LIVE_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', secret).update(JSON.stringify(event)).digest('hex');
        if (hash == req.headers['x-paystack-signature'] && validIps.includes(ip)) {

            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
                    }
                })
                if (event.data.status === "success") {
                    const updateUser = {
                        status: "PAID"
                    }
                    await BindingPayment.update(updateUser, {
                        where: {
                            user_id: event.data.metadata.user_id
                        }
                    })
                }
                    res.status(200).send();
            }else{
                const verifyPaymentHistory = paymentHistory.findOne({
                    where: {
                        txn_ref: event.data.reference,
                        username: event.data.metadata.matricNumber
                    }
                })
    
                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 findPaymentHistory = await paymentHistory.findOne({
                    where: {
                        txn_ref: event.data.reference,
                        username: event.data.metadata.matricNumber
                    }
                })
    
                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: 	findPaymentHistory.package_id
                    })
    
                    if (updatePaid && createSub){
                        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();
    }
}