import { useCallback, useEffect, useRef, useState } from "react";
const FOLDERS_PAGE_SIZE = 100;
function useUserFolders(ctx) {
    const [folders, setFolders] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const abortRef = useRef(null);
    const fetchFolders = useCallback(async ()=>{
        if (!ctx) return;
        abortRef.current?.abort();
        const ctrl = new AbortController();
        abortRef.current = ctrl;
        setLoading(true);
        setError(null);
        const base = (ctx.baseUrl ?? '').replace(/\/$/, '');
        const url = `${base}/${ctx.tenantName}/orchestrator_/api/FoldersNavigation/GetFoldersForCurrentUser?take=${FOLDERS_PAGE_SIZE}`;
        try {
            const res = await fetch(url, {
                headers: {
                    Authorization: `Bearer ${ctx.token}`,
                    Accept: 'application/json'
                },
                signal: ctrl.signal
            });
            if (!res.ok) throw new Error(`FoldersNavigation API ${res.status} ${res.statusText}`);
            const data = await res.json();
            if (!ctrl.signal.aborted) setFolders((data.PageItems ?? []).map((f)=>({
                    id: f.Key,
                    label: f.DisplayName,
                    numericId: f.Id
                })));
        } catch (err) {
            if (err?.name === 'AbortError') return;
            if (!ctrl.signal.aborted) setError(err instanceof Error ? err : new Error(String(err)));
        } finally{
            if (!ctrl.signal.aborted) setLoading(false);
        }
    }, [
        ctx
    ]);
    useEffect(()=>{
        if (!ctx) {
            abortRef.current?.abort();
            setFolders([]);
            setLoading(false);
            setError(null);
            return;
        }
        fetchFolders();
        return ()=>abortRef.current?.abort();
    }, [
        ctx,
        fetchFolders
    ]);
    return {
        folders,
        loading,
        error,
        refetch: fetchFolders
    };
}
const ORG_ADMIN_ROLES = [
    'ACCOUNT_ADMIN',
    'ACCOUNT_OWNER'
];
function useCanManageByo(ctx) {
    const [canManage, setCanManage] = useState(void 0);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const abortRef = useRef(null);
    useEffect(()=>{
        if (!ctx) {
            abortRef.current?.abort();
            setCanManage(void 0);
            setLoading(false);
            setError(null);
            return;
        }
        abortRef.current?.abort();
        const ctrl = new AbortController();
        abortRef.current = ctrl;
        setCanManage(void 0);
        setLoading(true);
        setError(null);
        const base = (ctx.baseUrl ?? '').replace(/\/$/, '');
        const url = `${base}/portal_/api/organization/UserOrganizationInfo`;
        fetch(url, {
            headers: {
                Authorization: `Bearer ${ctx.token}`,
                Accept: 'application/json'
            },
            signal: ctrl.signal
        }).then(async (res)=>{
            if (!res.ok) throw new Error(`UserOrganizationInfo API ${res.status} ${res.statusText}`);
            const data = await res.json();
            if (!ctrl.signal.aborted) setCanManage(ORG_ADMIN_ROLES.includes(data.accountRoleType ?? ''));
        }).catch((err)=>{
            if (err?.name === 'AbortError') return;
            if (!ctrl.signal.aborted) {
                setError(err instanceof Error ? err : new Error(String(err)));
                setCanManage(false);
            }
        }).finally(()=>{
            if (!ctrl.signal.aborted) setLoading(false);
        });
        return ()=>ctrl.abort();
    }, [
        ctx
    ]);
    return {
        canManage,
        loading,
        error
    };
}
function buildLlmConfigurationsUrl(ctx, options) {
    const base = (ctx.baseUrl ?? '').replace(/\/$/, '');
    const root = `${base}/portal_/admin/ai-trust-layer/llm-configurations`;
    const { intent, folderNumericId, configurationId } = options;
    if (ctx.tenantId && null != folderNumericId) {
        if ('edit' === intent && configurationId) return `${root}/${ctx.tenantId}/${folderNumericId}/edit/${encodeURIComponent(configurationId)}`;
        if ('add' === intent) {
            const params = new URLSearchParams();
            if (ctx.requestingProduct) params.set('product', ctx.requestingProduct);
            if (ctx.requestingFeature) params.set('feature', ctx.requestingFeature);
            const qs = params.toString();
            return `${root}/${ctx.tenantId}/${folderNumericId}/add${qs ? `?${qs}` : ''}`;
        }
    }
    const params = new URLSearchParams();
    if (ctx.tenantId) params.set('tenantId', ctx.tenantId);
    if (null != folderNumericId) params.set('folderId', String(folderNumericId));
    const qs = params.toString();
    return `${root}${qs ? `?${qs}` : ''}`;
}
const platformNavigation = {
    assign (url) {
        globalThis.location?.assign(url);
    }
};
export { buildLlmConfigurationsUrl, platformNavigation, useCanManageByo, useUserFolders };
