module.exports = Self => {
    Self.remoteMethod('sync', {
        description: 'Synchronizes the user with the other user databases',
        accepts: [
            {
                arg: 'userName',
                type: 'string',
                description: 'The user name',
                required: true
            }, {
                arg: 'password',
                type: 'string',
                description: 'The password'
            }, {
                arg: 'force',
                type: 'boolean',
                description: 'Whether to force synchronization'
            }
        ],
        http: {
            path: `/:userName/sync`,
            verb: 'PATCH'
        }
    });

    Self.sync = async function(userName, password, force) {
        let $ = Self.app.models;
        let user = await $.Account.findOne({
            fields: ['id'],
            where: {name: userName}
        });
        let isSync = !await $.UserSync.exists(userName);

        if (!force && isSync && user) return;
        await $.AccountConfig.syncUser(userName, password);
        await $.UserSync.destroyById(userName);
    };
};