module.exports = Self => {
    Self.remoteMethodCtx('new', {
        description: `Replaces the record or creates it if it doesn't exist`,
        accessType: 'READ',
        accepts: [
            {
                arg: 'saleFk',
                type: 'number',
                description: 'The sale id'
            },
            {
                arg: 'isChecked',
                type: 'boolean'
            },
            {
                arg: 'quantity',
                type: 'number'
            },
            {
                arg: 'stateCode',
                type: 'string'
            }
        ],
        returns: {
            type: ['object'],
            root: true
        },
        http: {
            path: `/new`,
            verb: 'POST'
        }
    });

    Self.new = async(ctx, saleFk, isChecked, quantity, stateCode, options) => {
        const models = Self.app.models;
        const userId = ctx.req.accessToken.userId;
        const myOptions = {};
        let tx;

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

        if (!myOptions.transaction) {
            tx = await Self.beginTransaction({});
            myOptions.transaction = tx;
        }
        try {
            const state = await models.State.findOne({
                where: {code: stateCode}
            }, myOptions);

            const saleTracking = await models.SaleTracking.findOne({
                where: {
                    saleFk: saleFk,
                    stateFk: state.id,
                    workerFk: userId
                }
            }, myOptions);

            let newSaleTracking;
            if (saleTracking) {
                newSaleTracking = await saleTracking.updateAttributes({
                    saleFk: saleFk,
                    stateFk: state.id,
                    workerFk: userId,
                    isChecked: isChecked,
                    originalQuantity: quantity,
                    isScanned: null
                }, myOptions);
            } else {
                newSaleTracking = await models.SaleTracking.create({
                    saleFk: saleFk,
                    stateFk: state.id,
                    workerFk: userId,
                    isChecked: isChecked,
                    originalQuantity: quantity,
                    isScanned: null
                }, myOptions);
            }

            if (tx) await tx.commit();

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