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)) {
            return createResponse(noPathSpecifiedMessage);

        const edgeGridInstance = new AkamaiEdgeGrid(

//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] });'Prepared request payload:', requestBody);

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

        log.debug('Authenticating with Akamai EdgeGrid...');
            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:',;
                } 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:',;
        return JSON.stringify(;

module.exports = { invalidateCache };