// tslint:disable:no-console
import * as mongoose from 'mongoose';

import { chevre } from '../../../lib/index';

mongoose.Model.on('index', (...args) => {
    console.error('******** index event emitted. ********\n', args);
});

async function main() {
    await mongoose.connect(<string>process.env.MONGOLAB_URI);

    const indexes = await mongoose.connection.db.collection('aggregateOffers')
        .indexes();
    console.log(indexes);
    console.log(indexes.length);

    const aggregateOfferRepo = await chevre.repository.AggregateOffer.createInstance(mongoose.connection);

    const offers = await aggregateOfferRepo.search(
        {
            limit: 10,
            // page: 1,
            project: { id: { $eq: String(process.env.PROJECT_ID) } },
            availability: { $eq: chevre.factory.itemAvailability.InStock },
            itemOffered: { typeOf: { $eq: chevre.factory.product.ProductType.EventService } },
            acceptedPaymentMethod: { identifier: { $in: ['xxx'] } },
            // identifier: { $eq: '901' },
            sort: {
                'priceSpecification.price': 1,
                identifier: 1
            }
        },
        {
            id: 1,
            identifier: 1,
            name: 1,
            priceSpecification: 1
        }
    );
    console.log(offers);
    console.log(offers[0]?.offers);
    console.log(offers.map((offer) => {
        return `${offer.project.id} ${(<any>offer).offerCount} ${offer.offers[0].identifier} ${offer.offers[0].name.ja} ${offer.offers[0].priceSpecification.price}`;
    }));
    console.log(offers.length);
}

main()
    .then(console.log)
    .catch(console.error);
