import { Fragment, jsx } from "react/jsx-runtime";
import { createContext, useContext, useMemo } from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useAPIClient, useRequest } from "../api-client/index.mjs";
import { useACLRoleContext } from "../built-in/acl/index.mjs";
import { useCompile } from "../schema-component/index.mjs";
const CurrentUserContext = /*#__PURE__*/ createContext(null);
CurrentUserContext.displayName = 'CurrentUserContext';
const useCurrentUserContext = ()=>useContext(CurrentUserContext);
const useCurrentRoles = ()=>{
    var _data_data;
    const { allowAnonymous } = useACLRoleContext();
    const { data } = useCurrentUserContext();
    const compile = useCompile();
    const options = useMemo(()=>{
        var _data_data;
        const roles = ((null == data ? void 0 : null == (_data_data = data.data) ? void 0 : _data_data.roles) || []).map((param)=>{
            let { name, title } = param;
            return {
                name,
                title: compile(title)
            };
        });
        if (allowAnonymous) roles.push({
            title: 'Anonymous',
            name: 'anonymous'
        });
        return roles;
    }, [
        allowAnonymous,
        null == data ? void 0 : null == (_data_data = data.data) ? void 0 : _data_data.roles
    ]);
    return options;
};
const CurrentUserProvider = (props)=>{
    const api = useAPIClient();
    const result = useRequest(()=>api.request({
            url: '/auth:check',
            skipNotify: true,
            skipAuth: true
        }).then((res)=>null == res ? void 0 : res.data));
    if (result.loading) return;
    return /*#__PURE__*/ jsx(CurrentUserContext.Provider, {
        value: result,
        children: props.children
    });
};
const NavigateIfNotSignIn = (param)=>{
    let { children } = param;
    var _result_data_data, _result_data;
    const result = useCurrentUserContext();
    const { pathname, search } = useLocation();
    const redirect = "?redirect=".concat(pathname).concat(search);
    if (!(null == result ? void 0 : null == (_result_data = result.data) ? void 0 : null == (_result_data_data = _result_data.data) ? void 0 : _result_data_data.id)) return /*#__PURE__*/ jsx(Navigate, {
        replace: true,
        to: "/signin".concat(redirect)
    });
    return /*#__PURE__*/ jsx(Fragment, {
        children: children
    });
};
export { CurrentUserContext, CurrentUserProvider, NavigateIfNotSignIn, useCurrentRoles, useCurrentUserContext };
