"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CloudFrontService = void 0;
const client_cloudfront_1 = require("@aws-sdk/client-cloudfront");
const console_1 = require("../lib/console");
const graphql_request_1 = require("graphql-request");
class CloudFrontService {
    constructor(client, options) {
        this.client = client;
        this.options = options;
    }
    createInvalidation(paths) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.options.distributionId) {
                throw new Error("Distribution id is not provided");
            }
            console_1.debug(`[cloudfront] Invalidate paths: ${JSON.stringify(paths)}`);
            paths.map((path) => {
                console.log(`[cloudfront] ISR Invalidate paths: ${path}`);
            });
            const res = yield this.client.send(new client_cloudfront_1.CreateInvalidationCommand({
                DistributionId: this.options.distributionId,
                InvalidationBatch: {
                    CallerReference: Date.now().toString(),
                    Paths: {
                        Quantity: paths.length,
                        Items: [...paths]
                    }
                }
            }));
        });
    }
    createRemoteInvalidation(paths, env) {
        return __awaiter(this, void 0, void 0, function* () {
            const endpoint = `https://seo-cronjob.${env}.getjerry.com/api/seo-cronjob/graphql`;
            const graphQLClient = new graphql_request_1.GraphQLClient(endpoint);
            const mutation = graphql_request_1.gql `
      mutation createRemoteInvalidation($urls: [String!]!) {
        invalidationUrls(urls: $urls)
      }
    `;
            console_1.debug(`[createRemoteInvalidation] send to ${endpoint}`);
            const data = yield graphQLClient.request(mutation, {
                urls: paths
            });
            console_1.debug(`[createRemoteInvalidation] result is ${JSON.stringify(data)}`);
        });
    }
}
exports.CloudFrontService = CloudFrontService;
