module.exports = Self => {
    Self.remoteMethodCtx('getVersion', {
        description: 'gets app version data',
        accessType: 'READ',
        accepts: [{
            arg: 'app',
            type: 'string',
            required: true
        }],
        returns: {
            type: ['object'],
            root: true
        },
        http: {
            path: `/getVersion`,
            verb: 'GET'
        }
    });

    Self.getVersion = async(ctx, app) => {
        const {models} = Self.app;
        const userId = ctx.req.accessToken.userId;

        const workerFk = await models.WorkerAppTester.findOne({
            where: {
                workerFk: userId
            }
        });
        let fields = ['id', 'appName'];

        if (workerFk)
            fields = fields.concat(['isVersionBetaCritical', 'versionBeta', 'urlBeta']);
        else
            fields = fields.concat(['isVersionCritical', 'version', 'urlProduction']);

        const filter = {
            where: {
                appName: app
            },
            fields,
        };

        const result = await Self.findOne(filter);
        return {
            isVersionCritical: result?.isVersionBetaCritical ?? result?.isVersionCritical,
            version: result?.versionBeta ?? result?.version,
            url: result?.urlBeta ?? result?.urlProduction
        };
    };
};