"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "register", {
    enumerable: true,
    get: function() {
        return register;
    }
});
const _expressasynchandler = /*#__PURE__*/ _interop_require_default(require("express-async-handler"));
const _errors = require("@tamanu/errors");
const _zod = require("zod");
const _constants = require("@tamanu/constants");
const _PortalOneTimeTokenService = require("./PortalOneTimeTokenService");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const RegistrationTokenSchema = _zod.z.string().refine((token)=>token.split('.').length === 2, {
    message: 'Token must contain exactly one period'
});
function parseRegistrationToken(token) {
    try {
        // Validate token format
        RegistrationTokenSchema.parse(token);
        // Split into parts after validation
        return token.split('.');
    } catch (error) {
        throw new _errors.BadAuthenticationError('Invalid registration token');
    }
}
const register = (0, _expressasynchandler.default)(async (req, res)=>{
    const { store, body } = req;
    const { models } = store;
    const { token } = body;
    if (!token) {
        throw new _errors.BadAuthenticationError('No registration token provided');
    }
    const [portalUserId, oneTimeToken] = parseRegistrationToken(token);
    const portalUser = await models.PortalUser.findByPk(portalUserId);
    if (!portalUser) {
        throw new _errors.BadAuthenticationError('Invalid registration token');
    }
    // If the user is already registered and verified,
    // don't continue verifying the token
    if (portalUser.status === _constants.PORTAL_USER_STATUSES.REGISTERED) {
        return res.status(200).json({
            message: 'User already registered'
        });
    }
    await store.sequelize.transaction(async ()=>{
        const oneTimeTokenService = new _PortalOneTimeTokenService.PortalOneTimeTokenService(models);
        await oneTimeTokenService.verifyAndConsume({
            portalUserId,
            token: oneTimeToken,
            type: _constants.PORTAL_ONE_TIME_TOKEN_TYPES.REGISTER
        });
        await models.PortalUser.update({
            status: _constants.PORTAL_USER_STATUSES.REGISTERED
        }, {
            where: {
                id: portalUserId
            }
        });
    });
    return res.status(200).json({
        message: 'User registered successfully'
    });
});

//# sourceMappingURL=register.js.map