"use strict";
/*
 * @adonisjs/auth
 *
 * (c) AdonisJS
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionClient = void 0;
const utils_1 = require("@poppinss/utils");
/**
 * Session client to login a user during tests using the
 * sessions guard
 */
class SessionClient {
    constructor(name, config, provider) {
        this.name = name;
        this.config = config;
        this.provider = provider;
    }
    /**
     * The name of the session key name
     */
    get sessionKeyName() {
        return `auth_${this.name}`;
    }
    /**
     * Returns the provider user instance from the regular user details. Raises
     * exception when id is missing
     */
    async getUserForLogin(user, identifierKey) {
        const providerUser = await this.provider.getUserFor(user);
        /**
         * Ensure id exists on the user
         */
        const id = providerUser.getId();
        if (!id) {
            throw new utils_1.Exception(`Cannot login user. Value of "${identifierKey}" is not defined`);
        }
        return providerUser;
    }
    /**
     * Returns the request data to mark user as logged in
     */
    async login(user) {
        /**
         * Since the login method is exposed to the end user, we cannot expect
         * them to instantiate and return an instance of authenticatable, so
         * we create one manually.
         */
        const providerUser = await this.getUserForLogin(user, this.config.provider.identifierKey);
        /**
         * getUserForLogin raises exception when id is missing, so we can
         * safely assume it is defined
         */
        const id = providerUser.getId();
        return {
            session: {
                [this.sessionKeyName]: id,
            },
        };
    }
    /**
     * No need to logout when using session client.
     * Session data is persisted within memory and will
     * be cleared after each test
     */
    async logout() { }
}
exports.SessionClient = SessionClient;
