const axios = require('axios');
const ProtonPaySettings = require('../model/ProtonPaySettings');

async function getProtonPayConfig() {
    return await ProtonPaySettings.findOne({ gatewayId: 'proton_pay' });
}

async function authenticateProtonPay() {
    // Proton Pay uses X-Key header, no separate authentication endpoint
    return true;
}

async function initiateProtonPayTransaction(payload) {
    try {
        const config = await getProtonPayConfig();
        
        if (!config || !config.status) {
            return {
                success: false,
                msg: "Proton Pay gateway is disabled or not configured"
            };
        }

        console.log("Proton Pay Config:", {
            baseUrl: config.baseUrl,
            merchantCode: config.merchantCode,
            apiKey: config.apiKey ? "***" + config.apiKey.slice(-4) : "Not set",
            status: config.status,
            minPayin: config.minPayin,
            maxPayin: config.maxPayin
        });

        // Validate amount against limits
        const amountInRupees = Number(payload.amount);
        if (amountInRupees < config.minPayin || amountInRupees > config.maxPayin) {
            return {
                success: false,
                msg: `Amount must be between ₹${config.minPayin} and ₹${config.maxPayin}`,
                code: 'INVALID_AMOUNT'
            };
        }

        // Convert amount to paise (minor units) - MUST BE INTEGER
        const amountInPaise = Math.round(amountInRupees * 100);
        
        // Prepare data similar to PHP code
        const requestData = {
            amount: amountInPaise,
            userName: payload.userName || `User${payload.userId}`,
            userId: String(payload.userId),
            phoneNumber: payload.phoneNumber || payload.customerMobile || "",
            email: payload.email || payload.customerEmail || "",
            merchantCode: config.merchantCode,
            merchantOrderId: payload.orderId,
            channel: 'trusted',
            returnUrl: config.returnUrl || 'https://api.protonpay.io/return'
        };

        console.log("Proton Pay Initiate Request:", {
            url: `${config.baseUrl}/api/payins/initiate`,
            data: requestData,
            amountInPaise: amountInPaise,
            amountInRupees: amountInRupees
        });
        
        // Step 1: Initialize Payin (GET payinId and payinUrl)
        const initResponse = await axios.post(
            `${config.baseUrl}/api/payins/initiate`,
            requestData,
            {
                headers: {
                    'Content-Type': 'application/json',
                    'X-Key': config.apiKey
                },
                timeout: 15000
            }
        );

        console.log("Proton Pay Initiate Response Status:", initResponse.status);
        console.log("Proton Pay Initiate Response Data:", initResponse.data);

        if (initResponse.status === 201) {
            const payinId = initResponse.data.payinId;
            const payinUrl = initResponse.data.payinUrl;
            
            // Step 2: Get UPI Link from assignment API (optional)
            let upiLink = null;
            try {
                const assignmentResponse = await axios.post(
                    `${config.baseUrl}/api/payins/assignment`,
                    {
                        merchantCode: config.merchantCode,
                        merchantOrderId: payload.orderId,
                        payinId: payinId
                    },
                    {
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Key': config.apiKey
                        },
                        timeout: 10000
                    }
                );

                if (assignmentResponse.status === 200) {
                    upiLink = assignmentResponse.data.upiLink;
                    console.log("Got UPI Link from assignment API:", upiLink);
                }
            } catch (assignmentError) {
                console.log("Assignment API failed, using payinUrl:", assignmentError.message);
                // Continue with payinUrl if assignment fails
            }

            return {
                success: true,
                data: {
                    transactionId: payinId,
                    intentUrl: upiLink || payinUrl, // Prefer UPI link if available
                    payinUrl: payinUrl,
                    upiLink: upiLink,
                    orderId: payload.orderId,
                    amount: payload.amount,
                    gateway: 'PROTONPAY',
                    merchantOrderId: payload.orderId,
                    payinId: payinId
                },
                rawResponse: initResponse.data
            };
        } else {
            return {
                success: false,
                msg: `Proton Pay initiation failed with status ${initResponse.status}`,
                code: 'INITIATION_FAILED',
                response: initResponse.data
            };
        }

    } catch (error) {
        console.error("Proton Pay Initiation Error:", {
            message: error.message,
            code: error.code,
            response: error.response?.data,
            status: error.response?.status,
            url: error.config?.url,
            headers: error.config?.headers ? {
                'X-Key': error.config.headers['X-Key'] ? "***" + error.config.headers['X-Key'].slice(-4) : "Not set"
            } : null
        });
        
        let errorMsg = "Proton Pay payment initiation failed";
        let errorCode = 'API_ERROR';
        
        if (error.response) {
            if (error.response.status === 400) {
                errorMsg = "Invalid request to Proton Pay";
            } else if (error.response.status === 461) {
                errorMsg = "Amount exceeds Proton Pay limits";
                errorCode = 'AMOUNT_LIMIT_EXCEEDED';
            } else if (error.response.status === 404) {
                errorMsg = "Invalid Proton Pay API key or merchant code";
                errorCode = 'INVALID_CREDENTIALS';
            } else if (error.response.data?.message) {
                errorMsg = `Proton Pay: ${error.response.data.message}`;
            } else if (error.response.data?.error) {
                errorMsg = `Proton Pay: ${error.response.data.error}`;
            }
        } else if (error.code === 'ENOTFOUND') {
            errorMsg = "Cannot connect to Proton Pay server. Please check the API URL";
            errorCode = 'CONNECTION_FAILED';
        } else if (error.code === 'ECONNREFUSED') {
            errorMsg = "Proton Pay server refused connection";
            errorCode = 'CONNECTION_REFUSED';
        } else if (error.code === 'ETIMEDOUT') {
            errorMsg = "Connection to Proton Pay timed out";
            errorCode = 'TIMEOUT';
        }

        return {
            success: false,
            msg: errorMsg,
            code: errorCode
        };
    }
}

async function checkProtonPayStatus(orderId, payinId) {
    try {
        const config = await getProtonPayConfig();
        
        if (!config) {
            return {
                success: false,
                msg: "Proton Pay configuration not found"
            };
        }

        const response = await axios.post(
            `${config.baseUrl}/api/payins/checkStatus`,
            {
                merchantCode: config.merchantCode,
                merchantOrderId: orderId,
                payinId: payinId
            },
            {
                headers: {
                    'Content-Type': 'application/json',
                    'X-Key': config.apiKey
                }
            }
        );

        return {
            success: true,
            data: response.data
        };

    } catch (error) {
        console.error("Proton Pay Status Check Error:", error);
        return {
            success: false,
            msg: error.response?.data?.message || "Failed to check Proton Pay status"
        };
    }
}

// Helper to generate random email/name (similar to PHP)
function generateRandomEmail() {
    return `user${Date.now()}@example.com`;
}

function generateRandomName() {
    return `User${Date.now()}`;
}

module.exports = {
    getProtonPayConfig,
    authenticateProtonPay,
    initiateProtonPayTransaction,
    checkProtonPayStatus,
    generateRandomEmail,
    generateRandomName
};
























// const axios = require('axios');
// const ProtonPaySettings = require('../model/ProtonPaySettings');

// async function getProtonPayConfig() {
//     return await ProtonPaySettings.findOne({ gatewayId: 'proton_pay' });
// }

// async function authenticateProtonPay() {
//     // Proton Pay uses X-Key header, no separate authentication endpoint
//     return true;
// }

// async function initiateProtonPayTransaction(payload) {
//     try {
//         const config = await getProtonPayConfig();
        
//         if (!config || !config.status) {
//             return {
//                 success: false,
//                 msg: "Proton Pay gateway is disabled or not configured"
//             };
//         }

//         // Validate amount against limits
//         const amountInRupees = Number(payload.amount);
//         if (amountInRupees < config.minPayin || amountInRupees > config.maxPayin) {
//             return {
//                 success: false,
//                 msg: `Amount must be between ₹${config.minPayin} and ₹${config.maxPayin}`,
//                 code: 'INVALID_AMOUNT'
//             };
//         }

//         // Convert amount to paise (minor units)
//         const amountInPaise = Math.round(amountInRupees * 100);
        
//         const response = await axios.post(
//             `${config.baseUrl}/api/payins/initiate`,
//             {
//                 amount: amountInPaise,
//                 userName: payload.userName || payload.customerName || "User",
//                 userId: String(payload.userId),
//                 phoneNumber: payload.customerMobile || "",
//                 email: payload.customerEmail || "",
//                 merchantCode: config.merchantCode,
//                 merchantOrderId: payload.orderId,
//                 returnUrl: config.returnUrl || 'https://api.protonpay.io/return',
//                 notifyUrl: config.notifyUrl,
//                 channel: 'trusted' // Default channel
//             },
//             {
//                 headers: {
//                     'Content-Type': 'application/json',
//                     'X-Key': config.apiKey
//                 },
//                 timeout: 10000
//             }
//         );

//         console.log("Proton Pay Initiate Response:", response.data);

//         if (response.status === 201) {
//             return {
//                 success: true,
//                 data: {
//                     transactionId: response.data.payinId,
//                     intentUrl: response.data.payinUrl,
//                     orderId: payload.orderId,
//                     amount: payload.amount,
//                     gateway: 'PROTONPAY'
//                 },
//                 rawResponse: response.data
//             };
//         } else {
//             return {
//                 success: false,
//                 msg: "Failed to initiate Proton Pay transaction",
//                 code: 'INITIATION_FAILED'
//             };
//         }

//     } catch (error) {
//         console.error("Proton Pay Initiation Error:", error.response?.data || error.message);
        
//         let errorMsg = "Proton Pay payment initiation failed";
//         if (error.response) {
//             if (error.response.status === 461) {
//                 errorMsg = "Amount exceeds Proton Pay limits";
//             } else if (error.response.status === 404) {
//                 errorMsg = "Invalid Proton Pay API key or merchant code";
//             } else if (error.response.data?.message) {
//                 errorMsg = error.response.data.message;
//             }
//         }

//         return {
//             success: false,
//             msg: errorMsg,
//             code: 'API_ERROR'
//         };
//     }
// }

// async function checkProtonPayStatus(orderId, payinId) {
//     try {
//         const config = await getProtonPayConfig();
        
//         if (!config) {
//             return {
//                 success: false,
//                 msg: "Proton Pay configuration not found"
//             };
//         }

//         const response = await axios.post(
//             `${config.baseUrl}/api/payins/checkStatus`,
//             {
//                 merchantCode: config.merchantCode,
//                 merchantOrderId: orderId,
//                 payinId: payinId
//             },
//             {
//                 headers: {
//                     'Content-Type': 'application/json',
//                     'X-Key': config.apiKey
//                 }
//             }
//         );

//         return {
//             success: true,
//             data: response.data
//         };

//     } catch (error) {
//         console.error("Proton Pay Status Check Error:", error);
//         return {
//             success: false,
//             msg: error.response?.data?.message || "Failed to check Proton Pay status"
//         };
//     }
// }

// module.exports = {
//     getProtonPayConfig,
//     authenticateProtonPay,
//     initiateProtonPayTransaction,
//     checkProtonPayStatus
// };















// const axios = require("axios");

// class ProtonPayService {
//   constructor() {
//     this.baseUrl = "https://api.protonpay.io"; // Base URL only
//     this.xKey = process.env.PROTONPAY_X_KEY || "bdjDSbVRMG4np8Mz"; // MerchantKey
//     this.merchantCode = process.env.PROTONPAY_MERCHANT_CODE || "desimatka999";
    
//     console.log("ProtonPay Service Initialized with:", {
//       merchantCode: this.merchantCode,
//       baseUrl: this.baseUrl
//     });
//   }

//   // Test API connectivity
//   async testConnection() {
//     try {
//       const response = await axios.get(`${this.baseUrl}`, {
//         timeout: 5000
//       });
//       console.log("ProtonPay API Test Response:", response.status, response.data);
//       return { success: true, message: "Connected to ProtonPay server" };
//     } catch (error) {
//       console.error("ProtonPay Connection Error:", error.message);
//       return { success: false, error: error.message };
//     }
//   }

//   // Step 1: Initialize Payment
//   async initializePayment(paymentData) {
//     try {
//       const { 
//         amount, 
//         orderId, 
//         userId, 
//         userName, 
//         phoneNumber, 
//         email,
//         returnUrl 
//       } = paymentData;

//       const payload = {
//         amount: Math.round(amount * 100), // Convert to paise
//         userName: String(userName),
//         userId: String(userId),
//         phoneNumber: String(phoneNumber),
//         email: String(email),
//         merchantCode: this.merchantCode,
//         merchantOrderId: orderId,
//         channel: 'trusted',
//         returnUrl: returnUrl || `${process.env.BASE_URL || 'http://localhost:3000'}/webhook/protonpay`
//       };

//       console.log("ProtonPay Initialize Request:", {
//         url: `${this.baseUrl}/api/payins/initiate`,
//         payload: payload
//       });

//       const response = await axios.post(
//         `${this.baseUrl}/api/payins/initiate`,
//         payload,
//         {
//           headers: {
//             'Content-Type': 'application/json',
//             'X-Key': this.xKey,
//             'Accept': 'application/json'
//           },
//           timeout: 15000
//         }
//       );

//       console.log("ProtonPay Initialize Response Status:", response.status);
//       console.log("ProtonPay Initialize Response Data:", response.data);

//       if (response.status === 201) {
//         return {
//           success: true,
//           payinId: response.data.payinId,
//           orderId: orderId,
//           gatewayResponse: response.data
//         };
//       }

//       return { 
//         success: false, 
//         error: "Failed to initialize payment",
//         gatewayResponse: response.data
//       };

//     } catch (error) {
//       console.error("ProtonPay Initialize Error Details:", {
//         message: error.message,
//         response: error.response?.data,
//         status: error.response?.status,
//         headers: error.response?.headers
//       });
//       return { 
//         success: false, 
//         error: error.response?.data || error.message,
//         statusCode: error.response?.status,
//         gatewayResponse: error.response?.data
//       };
//     }
//   }

//   // Step 2: Get UPI Link
//   async getUpiLink(orderId, payinId) {
//     try {
//       const payload = {
//         merchantCode: this.merchantCode,
//         merchantOrderId: orderId,
//         payinId: payinId
//       };

//       console.log("ProtonPay UPI Link Request:", {
//         url: `${this.baseUrl}/api/payins/assignment`,
//         payload: payload
//       });

//       const response = await axios.post(
//         `${this.baseUrl}/api/payins/assignment`,
//         payload,
//         {
//           headers: {
//             'Content-Type': 'application/json',
//             'X-Key': this.xKey,
//             'Accept': 'application/json'
//           },
//           timeout: 15000
//         }
//       );

//       console.log("ProtonPay UPI Link Response:", response.data);

//       if (response.status === 200) {
//         return {
//           success: true,
//           upiLink: response.data.upiLink,
//           gatewayResponse: response.data
//         };
//       }

//       return { 
//         success: false, 
//         error: "Failed to get UPI link",
//         gatewayResponse: response.data
//       };

//     } catch (error) {
//       console.error("ProtonPay UPI Link Error:", {
//         message: error.message,
//         response: error.response?.data,
//         status: error.response?.status
//       });
//       return { 
//         success: false, 
//         error: error.response?.data || error.message,
//         gatewayResponse: error.response?.data
//       };
//     }
//   }

//   // Check Payment Status (if API exists)
//   async checkPaymentStatus(orderId) {
//     try {
//       const response = await axios.get(
//         `${this.baseUrl}/api/payins/status/${orderId}`,
//         {
//           headers: {
//             'X-Key': this.xKey,
//             'Accept': 'application/json'
//           },
//           timeout: 10000
//         }
//       );

//       console.log("ProtonPay Status Response:", response.data);

//       if (response.status === 200) {
//         return {
//           success: true,
//           status: response.data.status,
//           gatewayResponse: response.data
//         };
//       }

//       return { 
//         success: false, 
//         error: response.data,
//         gatewayResponse: response.data
//       };

//     } catch (error) {
//       console.error("ProtonPay Status Check Error:", error.message);
//       // If endpoint doesn't exist, return default response
//       return { 
//         success: false, 
//         error: "Status check endpoint might not be available",
//         gatewayResponse: null
//       };
//     }
//   }
// }

// module.exports = new ProtonPayService();








// const axios = require("axios");

// class ProtonPayService {
//     constructor() {
//         this.baseUrl = process.env.PROTONPAY_BASE_URL || "https://api.protonpay.io/api";
//         this.xKey = process.env.PROTONPAY_X_KEY;
//         this.merchantCode = process.env.PROTONPAY_MERCHANT_CODE;

//         // Initialize credentials
//         this.init();
//     }

//     // Initialize with environment variables or dynamic config
//     init() {
//         // You can also load from database config later
//         console.log("ProtonPay Service Initialized");
//     }

//     // Update credentials (for admin panel)
//     updateCredentials(credentials) {
//         this.xKey = credentials.xKey;
//         this.merchantCode = credentials.merchantCode;
//         if (credentials.testMode) {
//             this.baseUrl = "https://testapi.protonpay.io/api";
//         }
//     }

//     // Step 1: Initialize Payment
//     async initializePayment(paymentData) {
//         try {
//             const {
//                 amount,
//                 orderId,
//                 userId,
//                 userName,
//                 phoneNumber,
//                 email,
//                 returnUrl
//             } = paymentData;

//             const payload = {
//                 amount: Math.round(amount * 100), // Convert to paise
//                 userName: String(userName),
//                 userId: String(userId),
//                 phoneNumber: String(phoneNumber),
//                 email: String(email),
//                 merchantCode: this.merchantCode,
//                 merchantOrderId: orderId,
//                 channel: 'trusted',
//                 returnUrl: returnUrl || `${process.env.BASE_URL}/webhook/protonpay`
//             };

//             console.log("ProtonPay Initialize Request:", payload);

//             const response = await axios.post(
//                 `${this.baseUrl}/payins/initiate`,
//                 payload,
//                 {
//                     headers: {
//                         'Content-Type': 'application/json',
//                         'X-Key': this.xKey,
//                         'Accept': 'application/json'
//                     },
//                     timeout: 15000
//                 }
//             );

//             console.log("ProtonPay Initialize Response:", response.data);

//             if (response.status === 201) {
//                 return {
//                     success: true,
//                     payinId: response.data.payinId,
//                     orderId: orderId,
//                     gatewayResponse: response.data
//                 };
//             }

//             return {
//                 success: false,
//                 error: response.data,
//                 gatewayResponse: response.data
//             };

//         } catch (error) {
//             console.error("ProtonPay Initialize Error:", error.response?.data || error.message);
//             return {
//                 success: false,
//                 error: error.response?.data || error.message,
//                 gatewayResponse: error.response?.data
//             };
//         }
//     }

//     // Step 2: Get UPI Link
//     async getUpiLink(orderId, payinId) {
//         try {
//             const payload = {
//                 merchantCode: this.merchantCode,
//                 merchantOrderId: orderId,
//                 payinId: payinId
//             };

//             console.log("ProtonPay UPI Link Request:", payload);

//             const response = await axios.post(
//                 `${this.baseUrl}/payins/assignment`,
//                 payload,
//                 {
//                     headers: {
//                         'Content-Type': 'application/json',
//                         'X-Key': this.xKey,
//                         'Accept': 'application/json'
//                     },
//                     timeout: 15000
//                 }
//             );

//             console.log("ProtonPay UPI Link Response:", response.data);

//             if (response.status === 200) {
//                 return {
//                     success: true,
//                     upiLink: response.data.upiLink,
//                     gatewayResponse: response.data
//                 };
//             }

//             return {
//                 success: false,
//                 error: response.data,
//                 gatewayResponse: response.data
//             };

//         } catch (error) {
//             console.error("ProtonPay UPI Link Error:", error.response?.data || error.message);
//             return {
//                 success: false,
//                 error: error.response?.data || error.message,
//                 gatewayResponse: error.response?.data
//             };
//         }
//     }

//     // Check Payment Status
//     async checkPaymentStatus(orderId) {
//         try {
//             const response = await axios.get(
//                 `${this.baseUrl}/payins/status/${orderId}`,
//                 {
//                     headers: {
//                         'X-Key': this.xKey,
//                         'Accept': 'application/json'
//                     },
//                     timeout: 10000
//                 }
//             );

//             console.log("ProtonPay Status Response:", response.data);

//             if (response.status === 200) {
//                 return {
//                     success: true,
//                     status: response.data.status,
//                     gatewayResponse: response.data
//                 };
//             }

//             return {
//                 success: false,
//                 error: response.data,
//                 gatewayResponse: response.data
//             };

//         } catch (error) {
//             console.error("ProtonPay Status Error:", error.response?.data || error.message);
//             return {
//                 success: false,
//                 error: error.response?.data || error.message,
//                 gatewayResponse: error.response?.data
//             };
//         }
//     }
// }

// module.exports = new ProtonPayService();


















// const axios = require('axios');
// const crypto = require('crypto');

// class ProtonPayService {
//     constructor() {
//         this.baseUrl = 'https://api.protonpay.io/api';
//         this.xKey = process.env.PROTONPAY_X_KEY;
//         this.merchantCode = process.env.PROTONPAY_MERCHANT_CODE;
//     }

//     // Step 1: Initialize Payin
//     async initializePayment(orderData) {
//         try {
//             const { amount, userId, userName, phoneNumber, email, orderId } = orderData;

//             const payload = {
//                 amount: Math.round(amount * 100), // Convert to minor units
//                 userName: String(userName),
//                 userId: String(userId),
//                 phoneNumber: String(phoneNumber),
//                 email: String(email),
//                 merchantCode: this.merchantCode,
//                 merchantOrderId: orderId,
//                 channel: 'trusted',
//                 returnUrl: `${process.env.BASE_URL}/api/payments/protonpay/webhook`
//             };

//             const response = await axios.post(
//                 `${this.baseUrl}/payins/initiate`,
//                 payload,
//                 {
//                     headers: {
//                         'Content-Type': 'application/json',
//                         'X-Key': this.xKey
//                     }
//                 }
//             );

//             if (response.status === 201) {
//                 return {
//                     success: true,
//                     payinId: response.data.payinId
//                 };
//             }

//             return { success: false, error: response.data };
//         } catch (error) {
//             console.error('ProtonPay Initialize Error:', error.response?.data || error.message);
//             return {
//                 success: false,
//                 error: error.response?.data || error.message
//             };
//         }
//     }

//     // Step 2: Get UPI Link
//     async getUpiLink(orderId, payinId) {
//         try {
//             const payload = {
//                 merchantCode: this.merchantCode,
//                 merchantOrderId: orderId,
//                 payinId: payinId
//             };

//             const response = await axios.post(
//                 `${this.baseUrl}/payins/assignment`,
//                 payload,
//                 {
//                     headers: {
//                         'Content-Type': 'application/json',
//                         'X-Key': this.xKey
//                     }
//                 }
//             );

//             if (response.status === 200) {
//                 return {
//                     success: true,
//                     upiLink: response.data.upiLink
//                 };
//             }

//             return { success: false, error: response.data };
//         } catch (error) {
//             console.error('ProtonPay UPI Link Error:', error.response?.data || error.message);
//             return {
//                 success: false,
//                 error: error.response?.data || error.message
//             };
//         }
//     }

//     // Verify webhook signature (if provided by ProtonPay)
//     verifyWebhookSignature(payload, signature) {
//         // Implement if ProtonPay provides webhook signature verification
//         // This is a placeholder - check ProtonPay documentation
//         return true;
//     }
// }

// module.exports = new ProtonPayService();