export function createChannelBusyStore(defaults = () => ({ processing: false, switching: false })) {
    const states = new Map();
    return {
        get(contextKey) {
            let state = states.get(contextKey);
            if (!state) {
                state = defaults();
                states.set(contextKey, state);
            }
            return state;
        },
        peek(contextKey) {
            return states.get(contextKey);
        },
        delete(contextKey) {
            states.delete(contextKey);
        },
    };
}
export function createChannelQueueStatusController(options) {
    const states = new Map();
    return {
        async update(contextKey, context, text) {
            const state = states.get(contextKey) ?? {};
            if (state.lastText === text && state.messageId) {
                return;
            }
            if (!state.messageId) {
                state.messageId = await options.send(contextKey, context, text);
                state.lastText = text;
                states.set(contextKey, state);
                return;
            }
            await options.edit(contextKey, context, state.messageId, text);
            state.lastText = text;
            states.set(contextKey, state);
        },
        delete(contextKey) {
            states.delete(contextKey);
        },
    };
}
export function createChannelActivityRecorder(options) {
    return (request, input) => {
        return options.activityStore.append({
            source: options.source,
            contextKey: request.contextKey,
            actor: input.actor ?? options.actorFor(request),
            workspace: input.workspace ?? options.workspace,
            threadId: input.threadId ?? null,
            ...input,
        });
    };
}
export function createChannelAuditRecorder(options) {
    return (request, input) => {
        options.auditLog.append({
            channelId: options.channelId,
            contextKey: input.contextKey ?? request.contextKey,
            actor: input.actor ?? options.actorFor(request),
            actorId: request.authUser?.user.id ?? options.actorIdFor(request),
            actorRole: request.authUser?.groups.map((group) => group.name).join(", ") ?? "unauthenticated",
            ...input,
        });
    };
}
export function createChannelPermissionChecker(userStore) {
    return (request, permission) => userStore.hasPermission(request.authUser, permission);
}
