"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uploadMobileBundle = uploadMobileBundle;
const fs_1 = require("fs");
const form_data_1 = __importDefault(require("form-data"));
const axios_1 = __importDefault(require("axios"));
const projectSetup_1 = require("./projectSetup");
const utils_1 = require("../utils");
const workspace_1 = require("./workspace");
/**
 * Upload a mobile bundle to the Apptile server
 * @param appId The ID of the app
 * @param bundleName The name of the bundle
 * @param os The operating system ('ios' or 'android')
 * @param apptileCookie The cookie for authentication
 * @returns Promise resolving to the upload result
 */
function uploadMobileBundle(appId, bundleName, os, apptileCookie) {
    return __awaiter(this, void 0, void 0, function* () {
        // Get the bundle file
        const { err: bundleErr, assetZip } = yield (0, projectSetup_1.getMobileBundle)(appId, bundleName, os);
        if (bundleErr || !assetZip) {
            throw new Error(`Failed to retrieve bundle: ${bundleErr || "Asset zip not found"}`);
        }
        // Get git shas
        const { err, gitsha, sdksha } = yield (0, projectSetup_1.getGitShas)(appId);
        if (err) {
            throw new Error(`Failed to retrieve git shas: ${err}`);
        }
        // Get app config
        const apptileConfig = yield (0, workspace_1.getAppConfigsFromFS)(appId);
        // Create form data
        const formData = new form_data_1.default();
        formData.append("assetZipFile", (0, fs_1.createReadStream)(assetZip));
        formData.append("uploadDestination", os === "ios" ? "ios-jsbundle" : "android-jsbundle");
        formData.append("gitsha", gitsha);
        formData.append("sdksha", sdksha);
        formData.append("tag", "sometag");
        // Create headers with cookie
        const headers = (0, utils_1.makeHeadersWithCookie)(apptileCookie, formData.getHeaders());
        // Make request to upload
        const response = yield axios_1.default.post(`${apptileConfig.APPTILE_BACKEND_URL}/${(0, utils_1.getMidUrlAppValue)()}/${appId}/upload`, formData, headers);
        // Handle errors
        if (response.status >= 400) {
            try {
                const errorMessage = response.data;
                throw new Error(`Failed to upload: ${errorMessage}`);
            }
            catch (err) {
                console.error("Unprocessable error:", err);
                throw err;
            }
        }
        return {
            status: response.status,
            data: response.data,
        };
    });
}
