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

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

const project = { id: String(process.env.PROJECT_ID) };

async function main() {
    await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });

    const transactionRepo = await chevre.repository.Transaction.createInstance(mongoose.connection);

    const cursor = transactionRepo.getCursor(
        {
            'project.id': { $eq: project.id },
            typeOf: { $eq: chevre.factory.transactionType.PlaceOrder },
            status: {
                $in: [
                    chevre.factory.transactionStatusType.Canceled,
                    chevre.factory.transactionStatusType.Expired
                ]
            },
            startDate: {
                $gte: moment('2025-04-10T15:00:00Z')
                    .toDate(),
                $lte: moment('2025-04-11T01:00:00Z')
                    .toDate()
            }
        },
        {
            project: 1,
            typeOf: 1,
            startDate: 1,
            object: 1,
            result: 1,
            agent: 1
        }
    );
    console.log('transactions found');

    let i = 0;
    let transactionByMemberCount = 0;
    await cursor.eachAsync(async (doc) => {
        i += 1;
        const transaction: Pick<
            chevre.factory.transaction.ITransaction<chevre.factory.transactionType.PlaceOrder>,
            'project' | 'object' | 'startDate' | 'result' | 'typeOf' | 'agent'
        > = doc.toObject();

        if (transaction.agent.id === '28v3ml7b8f74h2dqdvni7ntf25') {
            const publishedPaymentMethodId = transaction.object.paymentMethods?.paymentMethodId;
            if (typeof publishedPaymentMethodId === 'string') {
                console.log(transaction.project.id, transaction.agent.id, publishedPaymentMethodId, transaction.startDate, i);
                transactionByMemberCount += 1;
            }
        }
    });

    console.log(i, 'transactions checked');
    console.log(transactionByMemberCount, 'transactionByMember found');
}

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