module.exports = async function ({ services: { authTokenHandler } }) {
  async function doAuthLoginToken(req) {
    const { authTokenJwt, phoneModel = null, deviceUuid = null } = req.body

    // Validate the auth token JWT and extract the auth token
    const authToken = authTokenHandler.validateAuthToken(authTokenJwt)

    // Get or create user session (userId, deviceId, roles)
    const { userId, deviceId, roles } =
      await authTokenHandler.getOrCreateUserSession(
        authToken,
        phoneModel,
        deviceUuid
      )

    // Generate user JWT
    const userBearerJwt = await authTokenHandler.generateUserJwt(
      userId,
      deviceId,
      roles
    )

    return { userBearerJwt }
  }

  return [doAuthLoginToken]
}
