const UserError = require('vn-loopback/util/user-error');

module.exports = Self => {
    Self.remoteMethodCtx('lock', {
        description: 'Lock an app for the user',
        accessType: 'WRITE',
        accepts: [
            {
                arg: 'appName',
                type: 'string',
                required: true,
                description: 'The app name',
                http: {source: 'path'}

            }
        ],
        returns: {
            type: ['object'],
            root: true
        },
        http: {
            path: `/:appName/lock`,
            verb: 'POST'
        }
    });

    Self.lock = async(ctx, appName, options) => {
        const models = Self.app.models;
        const userId = ctx.req.accessToken.userId;
        const myOptions = {};
        const $t = ctx.req.__; // $translate

        let tx;

        if (typeof options == 'object')
            Object.assign(myOptions, options);

        if (!myOptions.transaction) {
            tx = await Self.beginTransaction({});
            myOptions.transaction = tx;
        }

        try {
            const mdbApp = await models.MdbApp.findById(appName, {fields: ['app', 'locked', 'userFk']}, myOptions);

            if (mdbApp.locked) {
                throw new UserError($t('App locked', {
                    userId: mdbApp.userFk
                }));
            }

            const updatedMdbApp = await mdbApp.updateAttributes({
                userFk: userId,
                locked: Date.vnNew()
            }, myOptions);

            if (tx) await tx.commit();

            return updatedMdbApp;
        } catch (e) {
            if (tx) await tx.rollback();

            throw e;
        }
    };
};