"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const forwardAudienceEvent_1 = __importDefault(require("./forwardAudienceEvent"));
const common_functions_1 = require("./common-functions");
const common_constants_1 = require("./common-constants");
const destination = {
    name: 'StackAdapt Audiences',
    slug: 'actions-stackadapt-audiences',
    description: 'Sync Segment Engage Audiences as well as user profile details to StackAdapt',
    mode: 'cloud',
    authentication: {
        scheme: 'custom',
        fields: {
            apiKey: {
                label: 'GraphQL Token',
                description: 'Your StackAdapt GQL API Token',
                type: 'password',
                required: true
            },
            advertiser_id: {
                label: 'Advertiser ID',
                description: 'The StackAdapt advertiser ID to add the profile to.',
                type: 'string',
                required: true
            }
        },
        testAuthentication: async (request) => {
            const scopeQuery = `query {
        tokenInfo {
          scopesByAdvertiser {
            nodes {
              advertiser {
                name
              }
              scopes
            }
          }
        }
      }`;
            const res = await request(common_constants_1.GQL_ENDPOINT, {
                body: JSON.stringify({ query: scopeQuery }),
                throwHttpErrors: false
            });
            if (res.status !== 200) {
                throw new Error(res.status + res.statusText);
            }
            const canWrite = (await res.json()).data?.tokenInfo?.scopesByAdvertiser?.nodes?.some((node) => node.scopes.includes('WRITE'));
            if (!canWrite) {
                throw new Error('Please verify your GQL Token or contact support');
            }
        }
    },
    extendRequest: ({ settings }) => {
        return {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${settings.apiKey}`
            }
        };
    },
    onDelete: async (request, { payload, settings }) => {
        const userId = payload.userId;
        const formattedExternalIds = `["${userId}"]`;
        const syncId = (0, common_functions_1.sha256hash)(String(userId));
        const advertiserId = settings.advertiser_id;
        const mutation = `mutation {
      deleteProfilesWithExternalIds(
        input: {
          externalIds: ${formattedExternalIds},
          externalProvider: "${common_constants_1.EXTERNAL_PROVIDER}",
          syncId: "${syncId}",
          advertiserIds: [${parseInt(advertiserId, 10)}]
        }
      ) {
        userErrors {
          message
          path
        }
      }
    }`;
        const response = await request(common_constants_1.GQL_ENDPOINT, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ query: mutation })
        });
        const result = await response.json();
        if (result.data.deleteProfilesWithExternalIds.userErrors.length > 0) {
            const errorMessages = result.data.deleteProfilesWithExternalIds.userErrors.map((e) => e.message).join(', ');
            throw new actions_core_1.IntegrationError(`Profile deletion was not successful: ${errorMessages}`, 'DELETE_FAILED', 400);
        }
        return result;
    },
    actions: {
        forwardAudienceEvent: forwardAudienceEvent_1.default
    }
};
exports.default = destination;
//# sourceMappingURL=index.js.map