// QuickBooks Payments API service
const { retryNetworkOperation, makeHttpsRequest } = require('../utils/network');
const { auditLog } = require('../utils/logging');

class QuickBooksPaymentsService {
    constructor(accessToken, environment = 'sandbox') {
        this.accessToken = accessToken;
        this.environment = environment;
        this.baseUrl = environment === 'production' 
            ? 'https://api.intuit.com' 
            : 'https://sandbox.api.intuit.com';
    }

    // Process payment through QuickBooks Payments API
    async processPayment(paymentData, req) {
        try {
            console.error('PAYMENT_PROCESSING: Starting payment with data:', JSON.stringify(paymentData, null, 2));
            
            const postData = JSON.stringify(paymentData);
            const options = {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                    'Request-Id': req?.requestId || 'no-request-id',
                    'Content-Length': Buffer.byteLength(postData)
                }
            };

            const apiUrl = `${this.baseUrl}/quickbooks/v4/payments/charges`;
            
            auditLog('PAYMENT_API_REQUEST', { 
                url: apiUrl, 
                amount: paymentData.amount,
                environment: this.environment
            }, req);

            const response = await makeHttpsRequest(apiUrl, options, postData);
            
            console.error('PAYMENT_PROCESSING: Response status:', response.status);
            console.error('PAYMENT_PROCESSING: Response data:', JSON.stringify(response.data, null, 2));
            
            return response;
        } catch (error) {
            console.error('PAYMENT_PROCESSING: Error processing payment:', error.message);
            throw error;
        }
    }

    // Get transaction details from QuickBooks Payments API
    async getTransactionDetails(transactionId, req) {
        try {
            const apiUrl = `${this.baseUrl}/quickbooks/v4/payments/charges/${transactionId}`;
            
            auditLog('GET_TRANSACTION_DETAILS_REQUEST', {
                url: apiUrl,
                transactionId: transactionId,
                environment: this.environment
            }, req);
            
            const options = {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + this.accessToken,
                    'Accept': 'application/json',
                    'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                    'Request-Id': req?.requestId || 'no-request-id'
                }
            };
            
            const response = await makeHttpsRequest(apiUrl, options);
            
            console.error('GET_TRANSACTION_DEBUG: Response Status:', response.status);
            console.error('GET_TRANSACTION_DEBUG: Response Data:', JSON.stringify(response.data, null, 2));
            
            return response;
        } catch (error) {
            console.error('GET_TRANSACTION_ERROR: Error fetching transaction details:', error.message);
            throw error;
        }
    }

    // Process refund through QuickBooks Payments API
    async processRefund(transactionId, refundData, req) {
        try {
            console.error('REFUND_PROCESSING: Starting refund for transaction:', transactionId);
            console.error('REFUND_PROCESSING: Input refund data:', JSON.stringify(refundData, null, 2));
            
            // QuickBooks Payments API v4 Refunds format:
            // - For partial refund: {"amount": "200.00"} (string, not object)
            // - For full refund: {} (empty body)
            // - No 'context' field (that's only for charges, not refunds)
            const qbRefundData = {};
            
            // Handle amount properly - either empty object for full refund or amount as string
            if (refundData.amount && parseFloat(refundData.amount) > 0) {
                qbRefundData.amount = parseFloat(refundData.amount).toFixed(2); // String format
                console.error('REFUND_PROCESSING: Partial refund amount:', qbRefundData.amount);
            } else {
                console.error('REFUND_PROCESSING: Full refund requested (empty body)');
            }
            
            console.error('REFUND_PROCESSING: Final QB refund data:', JSON.stringify(qbRefundData, null, 2));
            
            const postData = JSON.stringify(qbRefundData);
            const options = {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                    'Request-Id': req?.requestId || 'no-request-id',
                    'Content-Length': Buffer.byteLength(postData)
                }
            };

            const apiUrl = `${this.baseUrl}/quickbooks/v4/payments/charges/${transactionId}/refunds`;
            
            auditLog('REFUND_API_REQUEST', { 
                url: apiUrl, 
                transactionId, 
                originalRefundData: refundData,
                qbRefundData: qbRefundData,
                environment: this.environment
            }, req);

            console.error('REFUND_DEBUG: Full API URL:', apiUrl);
            console.error('REFUND_DEBUG: Request Headers:', JSON.stringify(options.headers, null, 2));
            console.error('REFUND_DEBUG: Request Body:', postData);
            console.error('REFUND_DEBUG: Request Body Length:', Buffer.byteLength(postData));
            console.error('REFUND_DEBUG: Environment:', this.environment);
            console.error('REFUND_DEBUG: Transaction ID:', transactionId);
            
            const response = await makeHttpsRequest(apiUrl, options, postData);
            
            console.error('REFUND_DEBUG: Response Status:', response.status);
            console.error('REFUND_DEBUG: Response Data:', JSON.stringify(response.data, null, 2));
            console.error('REFUND_DEBUG: Response Headers:', JSON.stringify(response.headers, null, 2));
            
            return response;
        } catch (error) {
            console.error('REFUND_PROCESSING: Error processing refund:', error.message);
            throw error;
        }
    }

    // Get transaction details
    async getTransaction(transactionId, req) {
        try {
            console.error('GET_TRANSACTION: Fetching transaction:', transactionId);
            
            const options = {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`,
                    'Accept': 'application/json',
                    'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                    'Request-Id': req?.requestId || 'no-request-id'
                }
            };

            const apiUrl = `${this.baseUrl}/quickbooks/v4/payments/charges/${transactionId}`;
            
            const response = await makeHttpsRequest(apiUrl, options);
            
            console.error('GET_TRANSACTION: Response status:', response.status);
            console.error('GET_TRANSACTION: Response data:', JSON.stringify(response.data, null, 2));
            
            return response;
        } catch (error) {
            console.error('GET_TRANSACTION: Error fetching transaction:', error.message);
            throw error;
        }
    }

    // Void transaction (for unsettled transactions)
    async voidTransaction(transactionId, req) {
        try {
            console.error('VOID_TRANSACTION: Voiding transaction:', transactionId);
            
            const options = {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'User-Agent': 'QuickBooks-Payment-Gateway/1.0',
                    'Request-Id': req?.requestId || 'no-request-id'
                }
            };

            const apiUrl = `${this.baseUrl}/quickbooks/v4/payments/charges/${transactionId}/void`;
            
            auditLog('VOID_API_REQUEST', { 
                url: apiUrl, 
                transactionId,
                environment: this.environment
            }, req);
            
            const response = await makeHttpsRequest(apiUrl, options);
            
            console.error('VOID_TRANSACTION: Response status:', response.status);
            console.error('VOID_TRANSACTION: Response data:', JSON.stringify(response.data, null, 2));
            
            return response;
        } catch (error) {
            console.error('VOID_TRANSACTION: Error voiding transaction:', error.message);
            throw error;
        }
    }
}

module.exports = QuickBooksPaymentsService;
