const AkamaiEdgeGrid = require('akamai-edgegrid');
const { isEmpty, createResponse, generateCacheTag } = require('../utils');

const noPathSpecifiedMessage = 'No paths provided for cache invalidation';

async function invalidateCache(log, resourcePath, akamaiSettings, typeOfInvalidation) {
    try {
        log.debug('Starting cache invalidation process');

        log.debug("Resource path provided:", resourcePath);

        // Verify if resource path is present
        if (isEmpty(resourcePath)) {
            log.debug(`${noPathSpecifiedMessage}`);
            return createResponse(noPathSpecifiedMessage);
        }

        const edgeGridInstance = new AkamaiEdgeGrid(
            akamaiSettings.clientToken,
            akamaiSettings.clientSecret,
            akamaiSettings.accessToken,
            akamaiSettings.host
        );

//you can have your own logic to generate the cache tag.
        const cacheTag = await generateCacheTag(log, akamaiSettings.environmentType, resourcePath);
        log.debug("Generated cache tag:", cacheTag);

        log.debug('Akamai EdgeGrid instance created successfully');
        const requestBody = JSON.stringify({ objects: [cacheTag] });
        log.info('Prepared request payload:', requestBody);

        const akamaiApiEndpoint = `/ccu/v3/invalidate/${typeOfInvalidation}/${akamaiSettings.network}`;

        log.debug('Authenticating with Akamai EdgeGrid...');
        edgeGridInstance.auth({
            path: akamaiApiEndpoint,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: requestBody
        });

        const akamaiResponse = await new Promise((resolve, reject) => {
            edgeGridInstance.send((err, res, body) => {
                if (err) {
                    log.error('Error from Akamai:', err.message);
                    log.error('Response error from Akamai:', err.response);
                    log.error('Details from Akamai error:', err.response.data);
                    reject(err);
                } else {
                    log.debug('Received response from Akamai:', res);
                    log.debug('Response body from Akamai:', body);
                    resolve({ res, body });
                }
            });
        });

        // Return the complete JSON response from Akamai
        return createResponse({
            response: akamaiResponse.body,
            request: requestBody
        });
    } catch (err) {
        // Log any encountered errors
        log.error('Akamai API encountered an error:', err.response.data);
        return JSON.stringify(err.response.data);
    }
}

module.exports = { invalidateCache };