"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = usePullSecret;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const api_1 = require("../../common/api");
const common_1 = require("../../common");
const access_token_api_1 = require("../../common/api/accounts-management-service/access-token-api");
/**
 * Standalone / disconnected UI: proxy serves GET /api/pull-secret with pull-secret JSON
 * `{ "auths": … }` extracted from the mounted Secret manifest (see assisted-disconnected-ui proxy).
 */
function fetchPullSecretFromBridge() {
    return tslib_1.__awaiter(this, void 0, void 0, function* () {
        const res = yield fetch('/api/pull-secret', { credentials: 'same-origin' });
        if (!res.ok) {
            throw new Error(`Unexpected status code ${res.status}`);
        }
        const text = (yield res.text()).trim();
        return text || undefined;
    });
}
function usePullSecret(isSingleClusterFeatureEnabled) {
    const [pullSecret, setPullSecret] = react_1.default.useState();
    const { addAlert } = (0, common_1.useAlerts)();
    const getPullSecret = react_1.default.useCallback(() => tslib_1.__awaiter(this, void 0, void 0, function* () {
        try {
            if (api_1.isInOcm) {
                const accessTokenCfg = yield access_token_api_1.AccessTokenAPI.fetchPullSecret();
                if (accessTokenCfg) {
                    setPullSecret(JSON.stringify(accessTokenCfg)); // unmarshalled response as a string
                }
                else {
                    setPullSecret('');
                }
                return;
            }
            if (isSingleClusterFeatureEnabled) {
                const fromBridge = yield fetchPullSecretFromBridge();
                setPullSecret(fromBridge !== null && fromBridge !== void 0 ? fromBridge : '');
                return;
            }
            // Non-OCM multinode flow: user enters pull secret manually.
            setPullSecret('');
        }
        catch (e) {
            (0, api_1.handleApiError)(e, (e) => {
                setPullSecret('');
                addAlert({ title: 'Failed to retrieve pull secret', message: (0, api_1.getApiErrorMessage)(e) });
            });
        }
    }), [addAlert, isSingleClusterFeatureEnabled]);
    react_1.default.useEffect(() => {
        if (!pullSecret) {
            void getPullSecret();
        }
    }, []); // eslint-disable-line react-hooks/exhaustive-deps
    return pullSecret;
}
//# sourceMappingURL=usePullSecret.js.map