module.exports = Self => {
    Self.remoteMethodCtx('removeFile', {
        description: 'Removes a client document',
        accessType: 'WRITE',
        accepts: {
            arg: 'id',
            type: 'number',
            description: 'The document id',
            http: {source: 'path'}
        },
        returns: {
            type: 'object',
            root: true
        },
        http: {
            path: `/:id/removeFile`,
            verb: 'POST'
        }
    });

    Self.removeFile = async(ctx, id, options) => {
        const myOptions = {};
        let tx;

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

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

        try {
            const clientDms = await Self.findById(id, null, myOptions);

            const targetDms = await Self.app.models.Dms.removeFile(ctx, clientDms.dmsFk, myOptions);

            if (!targetDms || !clientDms)
                throw new UserError('Try again');

            const clientDmsDestroyed = await clientDms.destroy(myOptions);

            if (tx) await tx.commit();

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