module.exports = Self => {
    Self.remoteMethod('listSaleTracking', {
        description: 'Returns all ticket sale trackings',
        accessType: 'READ',
        accepts: [{
            arg: 'filter',
            type: 'Object',
            required: false,
            description: 'Filter defining where and paginated data',
            http: {source: 'query'}
        }],
        returns: {
            type: ["Object"],
            root: true
        },
        http: {
            path: `/listSaleTracking`,
            verb: 'get'
        }
    });

    Self.listSaleTracking = async filter => {
        let where = '';
        let limit = '';
        let order = '';
        let params;

        if (filter) {
            let connector = Self.dataSource.connector;
            if (filter.where) {
                where = 'WHERE s.ticketFk = ?';
                params = [filter.where.ticketFk];
            }

            limit = connector._buildLimit(null, filter.limit, filter.skip);
            order = connector.buildOrderBy('Item', filter.order);
        }

        let query = `SELECT 
                        st.id, 
                        s.quantity, 
                        s.concept, 
                        s.itemFk, 
                        st.originalQuantity, 
                        st.created,
                        st.workerFk,
                        w.firstName,
                        w.name,
                        ste.name AS state
                    FROM saleTracking st 
                        JOIN sale s ON s.id = st.saleFK
                        JOIN worker w ON w.id = st.workerFk
                        JOIN ticketState ts ON ts.ticketFk = s.ticketFk
                        JOIN state ste ON ste.id = ts.stateFK ${where} ${order} ${limit}`;

        let trackings = await Self.rawSql(query, params);

        let salesFilter = {
            include: [
                {
                    relation: 'item',
                    scope: {
                        fields: ['itemFk', 'name'],
                        include: {
                            relation: 'tags',
                            scope: {
                                fields: ['tagFk', 'value'],
                                include: {
                                    relation: 'tag',
                                    scope: {
                                        fields: ['name']
                                    }
                                },
                                limit: 6
                            }
                        }
                    }
                }
            ],
            where: {ticketFk: filter.where.ticketFk}
        };

        let sales = await Self.app.models.Sale.find(salesFilter);

        trackings.forEach(tracking => {
            sales.forEach(sale => {
                if (tracking.itemFk == sale.itemFk)
                    tracking.item = sale.item();
            });
        });

        return trackings;
    };
};