import logger from '@adonisjs/core/services/logger';
import { AsyncLocalStorage } from 'node:async_hooks';
export class AKAuthContext {
    #storage = new AsyncLocalStorage();
    #findUserById;
    constructor(findUserById) {
        this.#findUserById = findUserById;
    }
    runWithCurrentUser(user, callback) {
        logger.trace(`AuthContext.runWithCurrentUser ${user.email}`);
        return this.#storage.run({ user, isAdmin: user.isAdmin }, callback);
    }
    runWithCurrentUserAnonymous(callback) {
        logger.trace(`AuthContext.runWithCurrentUserAnonymous`);
        return this.#storage.run({ user: undefined, isAdmin: false }, callback);
    }
    runWithIsAdmin(callback) {
        logger.trace(`authContext.runWithIsAdmin`);
        return this.#storage.run({ user: undefined, isAdmin: true }, callback);
    }
    get user() {
        const user = this.#storage.getStore()?.user;
        logger.trace(`AuthContext.user ${user?.email}`);
        return user;
    }
    get isAdmin() {
        const isAdmin = this.#storage.getStore()?.isAdmin ?? this.#storage.getStore()?.user?.isAdmin ?? false;
        logger.trace(`AuthContext.isAdmin ${isAdmin}`);
        return isAdmin;
    }
    get isAnonymous() {
        return this.user === undefined && !this.isAdmin;
    }
    map(handler) {
        if (this.isAdmin)
            return handler.admin(this.user);
        else if (this.user)
            return handler.user(this.user);
        return handler.anonymous();
    }
    snapshot() {
        return {
            userId: this.user?.id,
            isAdmin: this.isAdmin,
        };
    }
    async runWithSnapshot(snapshot, callback) {
        if (snapshot.userId) {
            const user = await this.#findUserById(snapshot.userId);
            return await this.#storage.run({ user, isAdmin: snapshot.isAdmin }, callback);
        }
        else
            return await this.#storage.run({ user: undefined, isAdmin: snapshot.isAdmin }, callback);
    }
}
//# sourceMappingURL=auth_context.js.map