"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.callAuth0Api = void 0;
const node_fetch_1 = __importDefault(require("node-fetch"));
const logger_1 = __importDefault(require("../../logger"));
const authM2MToken_1 = require("./authM2MToken");
const callAuth0Api = async ({ method, endpoint, body, useManagementApi = true, }) => {
    try {
        const token = useManagementApi ? await (0, authM2MToken_1.getManagementApiToken)() : null;
        const baseUrl = process.env.AUTH0_ISSUER_BASE_URL;
        const url = useManagementApi ? `${baseUrl}/api/v2${endpoint}` : `${baseUrl}${endpoint}`;
        const headers = {
            'Content-Type': 'application/json',
        };
        if (useManagementApi && token) {
            headers.Authorization = `Bearer ${token}`;
        }
        const response = await (0, node_fetch_1.default)(url, {
            method,
            headers,
            body: body ? JSON.stringify(body) : undefined,
        });
        if (!response.ok) {
            const error = await response.json();
            logger_1.default.error(`Auth0 API call failed: ${JSON.stringify(error)}`);
            throw new Error(error.message || 'Auth0 API call failed');
        }
        return await response.json();
    }
    catch (error) {
        logger_1.default.error(`Auth0 API error: ${error.message}`);
        throw error;
    }
};
exports.callAuth0Api = callAuth0Api;
//# sourceMappingURL=auth0Api.js.map