/*
 * Copyright (c) 2023-2025 Datalayer, Inc.
 * Distributed under the terms of the Modified BSD License.
 */
import { useEffect, useState } from 'react';
import { useCache } from './useCache.js';
import { coreStore, useIAMStore, useLayoutStore, useOrganizationStore, useSpaceStore, } from '../state/index.js';
import { asUser, ANONYMOUS_USER, ANONYMOUS_USER_TOKEN, } from '../models/index.js';
import { requestDatalayerAPI, } from '../api/DatalayerApi.js';
export const useIAM = (props = { user: undefined, token: undefined }) => {
    const { token } = props;
    const [iamState, setIAMState] = useState(props);
    const iamStore = useIAMStore();
    const layoutStore = useLayoutStore();
    const organizationStore = useOrganizationStore();
    const spaceStore = useSpaceStore();
    const { useWhoami, useLogout } = useCache();
    const { data: whoamiData } = useWhoami();
    const logoutMutation = useLogout();
    const loginAndNavigate = async (token, logout, refresh, navigate, homeRoute) => {
        try {
            const resp = await requestDatalayerAPI({
                url: `${iamStore.iamRunUrl}/api/iam/v1/login`,
                method: 'POST',
                body: { token },
            });
            if (resp.success && resp.token) {
                if (resp.is_provided_token_external === true) {
                    // The provided token is recognized as an external one, so store it as such...
                    iamStore.setExternalToken(token);
                }
                const user = asUser(resp.user);
                const responseToken = resp.token;
                setIAMState({ user, token: responseToken });
                refresh(responseToken);
                if (navigate && homeRoute) {
                    navigate(homeRoute);
                }
            }
            else {
                throw new Error('Invalid Token.');
            }
        }
        catch (error) {
            if (error.name === 'RunResponseError' &&
                error.response.status === 401) {
                console.log('Datalayer IAM has sent a 401 return code.');
                logout();
            }
            throw error;
        }
    };
    const setLogin = (user, token) => {
        iamStore.setLogin(user, token);
        setIAMState({
            user,
            token,
        });
    };
    const logout = () => {
        iamStore.logout();
        layoutStore.reset();
        organizationStore.updateOrganizations([]);
        spaceStore.updateSpaces([]);
        // Call TanStack Query logout mutation which will clear all caches
        logoutMutation.mutate();
        setIAMState({ user: ANONYMOUS_USER, token: ANONYMOUS_USER_TOKEN });
    };
    useEffect(() => {
        if (token && whoamiData) {
            if (whoamiData.success) {
                const user = asUser(whoamiData.profile);
                setIAMState({ user, token });
                iamStore.setLogin(user, token);
                // TODO centralize user settings management.
                const aiagentsRunUrl = user.settings?.aiAgentsUrl;
                if (aiagentsRunUrl) {
                    coreStore.getState().setConfiguration({
                        aiagentsRunUrl,
                    });
                }
            }
        }
    }, [token, whoamiData, iamStore]);
    return {
        user: iamState.user,
        token: iamState.token,
        loginAndNavigate,
        setLogin,
        logout,
    };
};
export default useIAM;
