"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthFactory = void 0;
const database_1 = require("../controllers/database");
const security_1 = require("../controllers/security");
const test_1 = require("../test");
class AuthFactory {
    constructor() {
        this.domainName = '_User';
    }
    async signIn(userModel, context, options) {
        const queryModel = { filter: { username: userModel.username }, return: [] };
        const wOptions = { bypassDomainVerification: true };
        const users = await (0, database_1.findDataByFilterInStore)(this.domainName, queryModel, context, (0, test_1.databaseFactory)(), wOptions, options);
        if (users && Array.isArray(users) && users.length === 1) {
            const user = users[0];
            if (await (0, security_1.comparePlainTextWithSaltedHash)(userModel.password, user.password ? user.password : user._hashed_password)) {
                delete user.password;
                delete user._hashed_password;
                delete user._acl;
                delete user._rperm;
                delete user._wperm;
                user.token = await (0, security_1.generateToken)({ uid: user.id }, options);
                return user;
            }
            else {
                throw new Error('Password is not valid');
            }
        }
        else {
            throw new Error('Username is not valid');
        }
    }
    async signUp(userModel, context, options) {
        const wOptions = { bypassDomainVerification: true };
        userModel.password = await (0, security_1.saltHashPlainText)(userModel?.password);
        const user = await (0, database_1.writeOneDataInStore)(this.domainName, userModel, context, (0, test_1.databaseFactory)(), wOptions, options);
        delete user.password;
        user.token = await (0, security_1.generateToken)({ uid: user.id }, options);
        return user;
    }
}
exports.AuthFactory = AuthFactory;
