"use client";
import { __awaiter } from '../../node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.mjs';

function redirectToCustomerPortal(_a) {
    return __awaiter(this, arguments, void 0, function* ({ customerPortalApiEndpoint, redirectToSignIn, returnUrl = window.location.href, }) {
        var _b;
        if (!customerPortalApiEndpoint) {
            console.error('Customer portal endpoint is not configured.');
            alert('Customer portal is temporarily unavailable.');
            return false;
        }
        try {
            const response = yield fetch(customerPortalApiEndpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    returnUrl,
                }),
            });
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                console.error('Received non-JSON response from customer portal API');
                return false;
            }
            const result = yield response.json();
            if (!response.ok) {
                const errorMessage = result.error || `Request failed with status ${response.status}`;
                console.error('Customer portal request failed:', errorMessage);
                if (response.status === 401 || response.status === 403) {
                    redirectToSignIn();
                    return true;
                }
                alert(`Operation failed: ${errorMessage}`);
                return false;
            }
            if (result.success && ((_b = result.data) === null || _b === void 0 ? void 0 : _b.sessionUrl)) {
                window.location.href = result.data.sessionUrl;
                return true;
            }
            console.error('Customer portal session response invalid', result);
            return false;
        }
        catch (error) {
            console.error('Error creating customer portal session:', error);
            return false;
        }
    });
}

export { redirectToCustomerPortal };
