"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapCloudProviderToPlatformType = exports.getApiVipDnsName = void 0;
const tslib_1 = require("tslib");
const _1 = require(".");
const apis_1 = require("./apis");
const common_1 = require("../../common");
const CpuArchitectureService_1 = require("./CpuArchitectureService");
const getApiVipDnsName = (ocmCluster) => {
    var _a, _b;
    let apiVipDnsname = '';
    let urlType = '';
    try {
        // Format of cluster.api.url: protocol://domain:port
        if ((_a = ocmCluster.api) === null || _a === void 0 ? void 0 : _a.url) {
            urlType = 'api';
            const apiVipUrl = new URL(ocmCluster.api.url);
            apiVipDnsname = apiVipUrl.hostname; // just domain is needed
        }
        else if ((_b = ocmCluster.console) === null || _b === void 0 ? void 0 : _b.url) {
            urlType = 'console';
            // Try to guess API URL from Console URL.
            // Assumption: the cluster is originated by Assisted Installer, so console URL format should be of a fixed format.
            // protocol://console-openshift-console.apps.[CLUSTER_NAME].[BASE_DOMAIN]"
            const consoleUrlHostname = new URL(ocmCluster.console.url).hostname;
            const APPS = '.apps.';
            apiVipDnsname =
                'api.' + consoleUrlHostname.substring(consoleUrlHostname.indexOf(APPS) + APPS.length);
        }
    }
    catch (e) {
        // can be ignored, the error type has been set already
    }
    return { apiVipDnsname, errorType: apiVipDnsname ? '' : urlType };
};
exports.getApiVipDnsName = getApiVipDnsName;
const mapCloudProviderToPlatformType = (cloudProviderId) => {
    let platformType = cloudProviderId;
    if (!common_1.SupportedPlatformIntegrations.includes(platformType) &&
        !common_1.NonPlatformIntegrations.includes(platformType)) {
        platformType = 'baremetal';
    }
    const platform = {
        type: platformType || 'baremetal',
    };
    if (platformType === 'external') {
        platform.external = {
            platformName: 'oci',
            cloudControllerManager: 'External',
        };
    }
    return platform;
};
exports.mapCloudProviderToPlatformType = mapCloudProviderToPlatformType;
const Day2ClusterService = {
    getOpenshiftClusterId(ocmCluster) {
        return ocmCluster && ocmCluster.external_id;
    },
    fetchCluster(ocmCluster, pullSecret) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const openshiftClusterId = Day2ClusterService.getOpenshiftClusterId(ocmCluster);
            if (!openshiftClusterId) {
                // error?
                return;
            }
            const day2ClusterId = yield Day2ClusterService.getDay2ClusterId(openshiftClusterId);
            if (day2ClusterId) {
                return Day2ClusterService.fetchClusterById(day2ClusterId);
            }
            return Day2ClusterService.createCluster(openshiftClusterId, ocmCluster.display_name || ocmCluster.name || openshiftClusterId, (0, exports.getApiVipDnsName)(ocmCluster).apiVipDnsname, pullSecret, ocmCluster.openshift_version, (0, CpuArchitectureService_1.mapOcmArchToCpuArchitecture)(ocmCluster.cpu_architecture) || common_1.CpuArchitecture.x86);
        });
    },
    fetchClusterById(clusterId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { data } = yield apis_1.ClustersAPI.get(clusterId);
            return data;
        });
    },
    getDay2ClusterId(openshiftClusterId) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { data: clusters } = yield apis_1.ClustersAPI.listByOpenshiftId(openshiftClusterId);
            const day2Clusters = clusters.filter((cluster) => cluster.kind === 'AddHostsCluster');
            if (day2Clusters.length > 0) {
                return day2Clusters[0].id;
            }
            return undefined;
        });
    },
    createCluster(openshiftClusterId, clusterName, apiVipDnsname, pullSecret, openshiftVersion, cpuArchitecture) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const { data: day2Cluster } = yield apis_1.ClustersAPI.registerAddHosts({
                openshiftClusterId, // used to both match OpenShift Cluster and as an assisted-installer ID
                name: `scale-up-${clusterName}`, // both cluster.name and cluster.display-name contain just UUID which fails AI validation (k8s naming conventions)
                apiVipDnsname,
                openshiftVersion,
            });
            // Create only the infraenv for the day1 cpu architecture
            yield _1.InfraEnvsService.create({
                name: _1.InfraEnvsService.makeInfraEnvName(cpuArchitecture, day2Cluster.name),
                pullSecret,
                clusterId: day2Cluster.id,
                openshiftVersion,
                cpuArchitecture,
            });
            return day2Cluster;
        });
    },
    /**
     * Complete the day2Cluster coming from AI polling with the data in the OCM cluster
     * @param day2Cluster Day2 cluster
     * @param ocmCluster OCM cluster
     */
    completeAiClusterWithOcmCluster: (day2Cluster, ocmCluster) => {
        var _a;
        let treakedCluster = day2Cluster;
        if (ocmCluster && day2Cluster) {
            treakedCluster = Object.assign(Object.assign({}, day2Cluster), { openshiftVersion: ocmCluster.openshift_version, 
                // The field "cpu_architecture" is calculated based on the existing hosts' architecture
                // It can be a specific architecture, or "multi" if hosts from several architectures have been discovered
                cpuArchitecture: (0, CpuArchitectureService_1.mapOcmArchToCpuArchitecture)(ocmCluster.cpu_architecture), platform: (0, exports.mapCloudProviderToPlatformType)((_a = ocmCluster.cloud_provider) === null || _a === void 0 ? void 0 : _a.id) });
        }
        return treakedCluster;
    },
};
exports.default = Day2ClusterService;
//# sourceMappingURL=Day2ClusterService.js.map