import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { apiMutate } from '../../useAxiosMutate';
import { LoadingIndicator } from '../../../UI/loading/LoadingIndicator';
import { ConfigService } from '../../../configService';
export function OutlookCallback() {
    const location = useLocation();
    useEffect(() => {
        const fetchData = async () => {
            const urlParams = new URLSearchParams(location.search);
            const code = urlParams.get('code');
            const token = urlParams.get('outlookAccessToken');
            if (code) {
                await exchangeCodeForToken(code);
                window.opener.postMessage('loginSuccess', '*');
            }
            else if (token) {
                localStorage.setItem('outlookAccessToken', token);
            }
        };
        fetchData();
    }, [location]);
    function addSecondsToCurrentTimeUnix(seconds) {
        return Date.now() + seconds * 1000;
    }
    const exchangeCodeForToken = async (code) => {
        try {
            if (!ConfigService.integrationV2ApiUrl) {
                throw new Error('REACT_APP_INTEGRATION_V2_API_BASE is undefined');
            }
            if (!ConfigService.config.UNITY_URL) {
                throw new Error('REACT_APP_UNITY_URL is undefined');
            }
            const response = await apiMutate(ConfigService.integrationV2ApiUrl, `OutlookIntegrationAccessToken/getAccessToken`, {
                method: "post",
                data: {
                    option: "code",
                    value: code,
                    redirectUri: ConfigService.config.UNITY_URL + "/aad_redirect"
                }
            });
            const data = await response.data;
            data.accessToken ? localStorage.setItem('outlookAccessToken', data.accessToken) : null;
            data.refreshToken ? localStorage.setItem('outlookRefreshToken', data.refreshToken) : null;
            data.expiresIn ? localStorage.setItem('outlookExpiresAt', addSecondsToCurrentTimeUnix(data.expiresIn)) : null;
            window.close();
        }
        catch (error) {
            console.error('Error exchanging code for token', error);
        }
    };
    return (React.createElement(React.Fragment, null, React.createElement(LoadingIndicator, null)));
}
//# sourceMappingURL=OutlookCallback.js.map