const sendgrid = require("@sendgrid/mail");
const firebase = require("firebase-admin");
const config = require('../config/config');
const {use} = require('express/lib/router');
const {getUsersList} = require('./user.controller');
const {toBoolean} = require('validator');

exports.createUser = ((user) => {
    return firebase
        .auth()
        .createUser({
            email: user.email,
            password: user.password,
            displayName: user.name
        });
});

exports.setUserRole = ((user_id, role)  => {
    return firebase
        .auth()
        .setCustomUserClaims(user_id, { role: role });
});

exports.updateUser = (async (user_id, user)  => {

    return firebase
        .auth()
        .updateUser(user_id, {
            ...user,
            disabled: user.disabled
        }).then(updatedUser => {
            return {
                id: updatedUser.uid,
                name: updatedUser.displayName || '',
                email: updatedUser.email || '',
                disabled: updatedUser.disabled,
                role: updatedUser.customClaims ? updatedUser.customClaims.role : '',
                created_at: updatedUser.metadata ? updatedUser.metadata.creationTime : '',
                last_signed_in: updatedUser.metadata ? updatedUser.metadata.lastSignInTime : ''
            }
        })
});

exports.deleteUser = (async (user_id)  => {

    return firebase
        .auth()
        .deleteUser(user_id);

});

exports.sendUserCredentials = ((email, password) => {

    const mail = {
        to: email,
        from: config.config.sendgrid.email,
        templateId: config.config.sendgrid.createUserTemplate,
        dynamicTemplateData: {
            email: email,
            password: password
        }
    };

    return sendgrid.send(mail);

});

exports.getUsersList = async (nextPage) => {

    const usersList = await firebase.auth().listUsers(1000, nextPage);
    const users = [];

    usersList.users.forEach(user => {
        const userInfo = user.toJSON();
        users.push({
            id: userInfo.uid,
            name: userInfo.displayName || '',
            email: userInfo.email || '',
            disabled: userInfo.disabled,
            role: userInfo.customClaims ? userInfo.customClaims.role : '',
            created_at: userInfo.metadata ? userInfo.metadata.creationTime : '',
            last_signed_in: userInfo.metadata ? userInfo.metadata.lastSignInTime : ''
        });
    });

    return users;

};
