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

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

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

// tslint:disable-next-line:max-func-body-length
async function main() {
    await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });

    const paymentServiceRepo = await chevre.repository.PaymentService.createInstance(mongoose.connection);

    const cursor = paymentServiceRepo.getCursor(
        {
            typeOf: {
                $in: [
                    chevre.factory.service.paymentService.PaymentServiceType.CreditCard,
                    chevre.factory.service.paymentService.PaymentServiceType.MovieTicket
                ]
            }
            // _id: { $eq: '5f9a4fed4f3709000abe6415' }
        },
        {
            _id: 1,
            availableChannel: 1,
            productID: 1,
            project: 1,
            typeOf: 1,
            serviceType: 1
        }
    );
    console.log('docs found');

    let i = 0;
    // let updateCount = 0;
    const unexpectedIds: string[] = [];
    await cursor.eachAsync(async (doc) => {
        i += 1;
        const paymentService: Pick<
            chevre.factory.service.paymentService.IService,
            'availableChannel' | 'id' | 'productID' | 'project' | 'typeOf' | 'serviceType'
        > = doc.toObject();

        console.log(
            'alreadyMigrated?', paymentService.project.id, paymentService.productID, i);
        if (typeof paymentService.id !== 'string') {
            throw new Error('id must be string');
        }

        let isUnique = false;
        const existingServices = await paymentServiceRepo.projectFields(
            {
                project: { id: { $eq: paymentService.project.id } },
                serviceType: { codeValue: { $eq: paymentService.serviceType.codeValue } }
            },
            ['id']
        );
        if (existingServices.length === 1 && existingServices.at(0)?.id === paymentService.id) {
            isUnique = true;
        }

        if (isUnique) {
            console.log(
                'unique.', paymentService.project.id, paymentService.productID, i);
        } else {
            unexpectedIds.push(paymentService.productID);
        }
    });

    console.log(unexpectedIds);
    console.log(i, 'docs checked');
    console.log(unexpectedIds.length, 'docs unexpected');
}

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