"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
class ApplePortalSessionService {
    constructor($applePortalCookieService, $httpClient, $logger) {
        this.$applePortalCookieService = $applePortalCookieService;
        this.$httpClient = $httpClient;
        this.$logger = $logger;
        this.loginConfigEndpoint = "https://appstoreconnect.apple.com/olympus/v1/app/config?hostname=itunesconnect.apple.com";
        this.defaultLoginConfig = {
            authServiceUrl: "https://idmsa.apple.com/appleautcodh",
            authServiceKey: "e0b80c3bf78523bfe80974d320935bfa30add02e1bff88ec2166c6bd5a706c42"
        };
    }
    createUserSession(credentials) {
        return __awaiter(this, void 0, void 0, function* () {
            const loginConfig = yield this.getLoginConfig();
            const loginUrl = `${loginConfig.authServiceUrl}/auth/signin`;
            const loginResponse = yield this.$httpClient.httpRequest({
                url: loginUrl,
                method: "POST",
                body: JSON.stringify({
                    accountName: credentials.username,
                    password: credentials.password,
                    rememberMe: true
                }),
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-Apple-Widget-Key': loginConfig.authServiceKey,
                    'Accept': 'application/json, text/javascript'
                }
            });
            this.$applePortalCookieService.updateUserSessionCookie(loginResponse.headers["set-cookie"]);
            const sessionResponse = yield this.$httpClient.httpRequest({
                url: "https://appstoreconnect.apple.com/olympus/v1/session",
                method: "GET",
                headers: {
                    'Cookie': this.$applePortalCookieService.getUserSessionCookie()
                }
            });
            this.$applePortalCookieService.updateUserSessionCookie(sessionResponse.headers["set-cookie"]);
            const userDetailResponse = yield this.$httpClient.httpRequest({
                url: "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/user/detail",
                method: "GET",
                headers: {
                    'Content-Type': 'application/json',
                    'Cookie': this.$applePortalCookieService.getUserSessionCookie(),
                }
            });
            this.$applePortalCookieService.updateUserSessionCookie(userDetailResponse.headers["set-cookie"]);
            return JSON.parse(userDetailResponse.body).data;
        });
    }
    createWebSession(contentProviderId, dsId) {
        return __awaiter(this, void 0, void 0, function* () {
            const webSessionResponse = yield this.$httpClient.httpRequest({
                url: "https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/v1/session/webSession",
                method: "POST",
                body: JSON.stringify({
                    contentProviderId,
                    dsId,
                    ipAddress: null
                }),
                headers: {
                    'Accept': 'application/json, text/plain, */*',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'X-Csrf-Itc': 'itc',
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Cookie': this.$applePortalCookieService.getUserSessionCookie()
                }
            });
            const webSessionCookie = this.$applePortalCookieService.getWebSessionCookie(webSessionResponse.headers["set-cookie"]);
            return webSessionCookie;
        });
    }
    getLoginConfig() {
        return __awaiter(this, void 0, void 0, function* () {
            let config = null;
            try {
                const response = yield this.$httpClient.httpRequest({ url: this.loginConfigEndpoint, method: "GET" });
                config = JSON.parse(response.body);
            }
            catch (err) {
                this.$logger.trace(`Error while executing request to ${this.loginConfigEndpoint}. More info: ${err}`);
            }
            return config || this.defaultLoginConfig;
        });
    }
}
exports.ApplePortalSessionService = ApplePortalSessionService;
$injector.register("applePortalSessionService", ApplePortalSessionService);
