"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApplePortalApplicationService = void 0;
const yok_1 = require("../../common/yok");
const _ = require("lodash");
class ApplePortalApplicationService {
    constructor($applePortalSessionService, $errors, $httpClient) {
        this.$applePortalSessionService = $applePortalSessionService;
        this.$errors = $errors;
        this.$httpClient = $httpClient;
    }
    async getApplications(user) {
        let result = [];
        for (const account of user.associatedAccounts) {
            const contentProviderId = account.contentProvider.contentProviderId;
            const applications = await this.getApplicationsByProvider(contentProviderId);
            result = result.concat(applications.summaries);
        }
        return result;
    }
    async getApplicationsByProvider(contentProviderId) {
        const webSessionCookie = await this.$applePortalSessionService.createWebSession(contentProviderId);
        const summaries = [];
        await this.getApplicationsByUrl(webSessionCookie, "https://appstoreconnect.apple.com/iris/v1/apps?include=appStoreVersions", summaries);
        return { summaries: summaries };
    }
    async getApplicationsByUrl(webSessionCookie, url, summaries) {
        const response = await this.$httpClient.httpRequest({
            url,
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                Cookie: webSessionCookie,
            },
        });
        const result = JSON.parse(response.body);
        const data = result.data;
        for (const app of data) {
            let summary;
            summary = {
                bundleId: app.attributes.bundleId,
                adamId: app.id,
                name: app.attributes.name,
                versionSets: [],
            };
            summaries.push(summary);
        }
        if (result.links.next) {
            await this.getApplicationsByUrl(webSessionCookie, result.links.next, summaries);
        }
    }
    async getApplicationByBundleId(user, bundleId) {
        const applications = await this.getApplications(user);
        if (!applications || !applications.length) {
            this.$errors.fail(`Cannot find any registered applications for Apple ID ${user.userName} in iTunes Connect.`);
        }
        const application = _.find(applications, (app) => app.bundleId === bundleId);
        if (!application) {
            this.$errors.fail(`Cannot find registered applications that match the specified identifier ${bundleId} in iTunes Connect.`);
        }
        return application;
    }
}
exports.ApplePortalApplicationService = ApplePortalApplicationService;
yok_1.injector.register("applePortalApplicationService", ApplePortalApplicationService);
