module.exports = Self => {
    Self.remoteMethodCtx('deny', {
        description: 'sets a ticket request to denied and returns the changes',
        accessType: 'WRITE',
        accepts: [{
            arg: 'id',
            type: 'number',
            required: true,
            description: 'The request ID',
        }, {
            arg: 'observation',
            type: 'String',
            required: true,
            description: 'The request observation',
        }],
        returns: {
            type: 'number',
            root: true
        },
        http: {
            path: `/:id/deny`,
            verb: 'post'
        }
    });

    Self.deny = async(ctx, options) => {
        const models = Self.app.models;
        const $t = ctx.req.__; // $translate
        const myOptions = {};
        let tx;

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

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

        try {
            const userId = ctx.req.accessToken.userId;
            const worker = await Self.app.models.Worker.findOne({where: {id: userId}}, myOptions);

            const params = {
                isOk: false,
                attenderFk: worker.id,
                response: ctx.args.observation,
            };

            const request = await Self.app.models.TicketRequest.findById(ctx.args.id, null, myOptions);
            await request.updateAttributes(params, myOptions);

            const url = await Self.app.models.Url.getUrl();
            const requesterId = request.requesterFk;

            const message = $t('Deny buy request', {
                ticketId: request.ticketFk,
                url: `${url}ticket/${request.ticketFk}/request/index`,
                observation: params.response
            });

            await models.Chat.sendCheckingPresence(ctx, requesterId, message, myOptions);

            if (tx) await tx.commit();

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