public with sharing class PDFGenerationProxy {
    
    @AuraEnabled
    public static Map<String, Object> generatePDFFromHTML(String htmlContent, String pageSize) {
        try {
            // Validate HTML content
            if (String.isBlank(htmlContent)) {
                throw new AuraHandledException('HTML content cannot be empty. Please provide valid HTML content.');
            }
            
            
            // Call the Node.js API with return_download_link: true
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            
            // Set the endpoint URL
            request.setEndpoint('https://salesforce.tech4biz.io/generate-pdf');
            request.setMethod('POST');
            request.setHeader('Content-Type', 'application/json');
            request.setTimeout(120000); // 2 minutes timeout
            
            // Ensure relative resource URLs resolve to Salesforce domain by injecting <base>
            String modifiedHtml = htmlContent;
            String baseUrl = null;
            try {
                baseUrl = URL.getOrgDomainUrl().toExternalForm();
                if (modifiedHtml != null && !modifiedHtml.toLowerCase().contains('<base ')) {
                    String lower = modifiedHtml.toLowerCase();
                    Integer headIdx = lower.indexOf('<head>');
                    if (headIdx >= 0) {
                        Integer insertPos = headIdx + 6; // after <head>
                        modifiedHtml = modifiedHtml.substring(0, insertPos) + '<base href=\'' + baseUrl + '/\' />' + modifiedHtml.substring(insertPos);
                    } else {
                        // Prepend base if no head tag found
                        modifiedHtml = '<head><base href=\'' + baseUrl + '/\' /></head>' + modifiedHtml;
                    }
                }
            } catch (Exception e) {
                // best-effort only
            }

            // Prepare the request body
            Map<String, Object> requestBody = new Map<String, Object>();
            requestBody.put('input', modifiedHtml);
            requestBody.put('return_download_link', true);
            // Use 'format' for the Node API, keep page_size for backward-compat
            String formatVal = String.isNotBlank(pageSize) ? pageSize : 'A4';
            requestBody.put('format', formatVal);
            requestBody.put('page_size', formatVal);
            
            
            String jsonBody = JSON.serialize(requestBody);
            request.setBody(jsonBody);
            
            
            // Make the HTTP call
            HttpResponse response = http.send(request);
            
            
            if (response.getStatusCode() == 200) {
                // Parse the response
                Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                
                // Add additional metadata
                result.put('salesforce_generated_at', Datetime.now().format('yyyy-MM-dd HH:mm:ss'));
                result.put('api_version', '7.0.0');
                result.put('backend_status', 'NODE_JS_API_ACTIVE');
                
                return result;
            } else {
                // Handle error response
                Map<String, Object> errorResult = new Map<String, Object>();
                errorResult.put('success', false);
                errorResult.put('error', 'PDF generation failed: HTTP ' + response.getStatusCode());
                errorResult.put('message', response.getBody());
                errorResult.put('pdf_id', 'ERROR_' + DateTime.now().getTime());
                
                return errorResult;
            }
            
        } catch (Exception e) {
            
            Map<String, Object> errorResult = new Map<String, Object>();
            errorResult.put('success', false);
            errorResult.put('error', 'PDF generation failed: ' + e.getMessage());
            errorResult.put('pdf_id', 'ERROR_' + DateTime.now().getTime());
            errorResult.put('suggestion', 'Please try again or contact support.');
            
            return errorResult;
        }
    }
    
    @AuraEnabled
    public static Map<String, Object> generateCompressedPDF(String htmlContent, String pageSize) {
        try {
            // Validate HTML content
            if (String.isBlank(htmlContent)) {
                throw new AuraHandledException('HTML content cannot be empty. Please provide valid HTML content.');
            }
            
            
            // Call the Node.js API with return_download_link: true
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            
            // Set the endpoint URL
            request.setEndpoint('https://salesforce.tech4biz.io/generate-pdf');
            request.setMethod('POST');
            request.setHeader('Content-Type', 'application/json');
            request.setTimeout(120000); // 2 minutes timeout
            
            // Prepare the request body
            Map<String, Object> requestBody = new Map<String, Object>();
            requestBody.put('input', htmlContent);
            requestBody.put('return_download_link', true);
            if (String.isNotBlank(pageSize)) {
                requestBody.put('page_size', pageSize);
            }
            
            String jsonBody = JSON.serialize(requestBody);
            request.setBody(jsonBody);
            
            
            // Make the HTTP call
            HttpResponse response = http.send(request);
            
            
            if (response.getStatusCode() == 200) {
                // Parse the response
                Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                
                // Add compression-specific metadata
                result.put('compression_applied', true);
                result.put('compression_level', 'aggressive');
                result.put('status', 'compressed_download_ready');
                result.put('salesforce_generated_at', Datetime.now().format('yyyy-MM-dd HH:mm:ss'));
                result.put('api_version', '7.0.0');
                result.put('backend_status', 'NODE_JS_API_ACTIVE');
                
                return result;
            } else {
                // Handle error response
                Map<String, Object> errorResult = new Map<String, Object>();
                errorResult.put('success', false);
                errorResult.put('error', 'Compressed PDF generation failed: HTTP ' + response.getStatusCode());
                errorResult.put('message', response.getBody());
                errorResult.put('pdf_id', 'ERROR_' + DateTime.now().getTime());
                
                return errorResult;
            }
            
        } catch (Exception e) {
            
            Map<String, Object> errorResult = new Map<String, Object>();
            errorResult.put('success', false);
            errorResult.put('error', 'Compressed PDF generation failed: ' + e.getMessage());
            errorResult.put('pdf_id', 'ERROR_' + DateTime.now().getTime());
            errorResult.put('suggestion', 'Please try again or contact support.');
            
            return errorResult;
        }
    }
    
    @AuraEnabled
    public static String testAPIConnection() {
        try {
            String testHtml = '<html><body><h1>Test PDF Generation</h1><p>This is a test to verify the API connection.</p></body></html>';
            Map<String, Object> result = generatePDFFromHTML(testHtml, 'A4');
            return JSON.serialize(result);
        } catch (Exception e) {
            return 'Error testing API connection: ' + e.getMessage();
        }
    }
}
