const axios = require('axios');
const tokenLifespan = 10;
module.exports = Self => {
    Self.remoteMethodCtx('getServiceAuth', {
        description: 'Authenticates with the service and request a new token',
        accessType: 'READ',
        accepts: [],
        returns: {
            type: 'object',
            root: true
        },
        http: {
            path: `/getServiceAuth`,
            verb: 'GET'
        }
    });

    Self.getServiceAuth = async() => {
        if (!this.login)
            this.login = await requestToken();

        if (!this.login) return;

        if (Date.vnNow() > this.login.expires)
            this.login = await requestToken();

        return this.login;
    };

    /**
     * Requests a new Rocketchat token
     */
    async function requestToken() {
        const models = Self.app.models;
        const chatConfig = await models.ChatConfig.findOne();

        const {data} = await axios.post(`${chatConfig.api}/login`, {
            user: chatConfig.user,
            password: chatConfig.password
        });

        const requestData = data.data;
        if (requestData) {
            return {
                host: chatConfig.host,
                api: chatConfig.api,
                auth: {
                    userId: requestData.userId,
                    token: requestData.authToken
                },
                expires: Date.vnNow() + (1000 * 60 * tokenLifespan)
            };
        }
    }
};