// tslint:disable:no-console
import * as moment from 'moment';
import * as mongoose from 'mongoose';
import { call as deletePerson } from '../../../lib/chevre/service/task/deletePerson';
import { chevre } from '../../../lib/index';

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

    const settingRepo = await chevre.repository.Setting.createInstance(mongoose.connection);
    const setting = await settingRepo.findOne({ project: { id: { $eq: '*' } } }, ['userPoolIdNew']);
    if (typeof setting?.userPoolIdNew !== 'string') {
        throw new chevre.factory.errors.NotFound('setting.userPoolIdNew');
    }

    const DISCONTINUE_PEOPLE_PROJECT = process.env.USE_DISCONTINUE_PEOPLE_PROJECT;
    if (typeof DISCONTINUE_PEOPLE_PROJECT === 'string' && DISCONTINUE_PEOPLE_PROJECT.length > 0) {
        const ownershipInfoRepo = await chevre.repository.OwnershipInfo.createInstance(mongoose.connection);
        // const deletingOwnershipInfos = (await ownershipInfoRepo.projectFields({
        //     limit: NUM_TASKS,
        //     page: 1,
        //     sort: { ownedFrom: chevre.factory.sortType.Ascending },
        //     project: { id: { $eq: DISCONTINUE_PEOPLE_PROJECT } },
        //     ownedBy: {
        //         typeOf: { $eq: chevre.factory.personType.Person }
        //     },
        //     typeOfGood: {
        //         issuedThrough: {
        //             typeOf: {
        //                 $eq: chevre.factory.product.ProductType.EventService
        //             }
        //         }
        //     }
        // }));
        // console.log(deletingOwnershipInfos.length, 'deletingOwnershipInfos found');

        const cursor = ownershipInfoRepo.getCursor(
            {
                // sort: { ownedFrom: chevre.factory.sortType.Ascending },
                'project.id': { $eq: DISCONTINUE_PEOPLE_PROJECT },
                'ownedBy.typeOf': {
                    $exists: true,
                    $eq: chevre.factory.personType.Person
                },
                'typeOfGood.issuedThrough.typeOf': {
                    $exists: true,
                    $eq: chevre.factory.product.ProductType.EventService
                },
                ownedFrom: {
                    $lte: moment('2024-02-25T00:00:00Z')
                        .toDate()
                }
            },
            {
                _id: 1,
                ownedBy: 1,
                ownedFrom: 1,
                project: 1
            }
        );
        console.log('docs found');

        const runsAt: Date = new Date();
        const userPoolId: string = setting.userPoolIdNew;

        let i = 0;
        // tslint:disable-next-line:max-func-body-length
        await cursor.eachAsync(async (doc) => {
            i += 1;

            const deletingOwnershipInfo: Pick<
                chevre.factory.ownershipInfo.IOwnershipInfo<any>,
                'id' | 'ownedBy' | 'ownedFrom' | 'project'
            > = doc.toObject();
            const personId: string = (Array.isArray(deletingOwnershipInfo.ownedBy))
                ? deletingOwnershipInfo.ownedBy[0]?.id
                : deletingOwnershipInfo.ownedBy.id;
            console.log(deletingOwnershipInfo);

            console.log(
                'deleting person...',
                personId, deletingOwnershipInfo.project.id, deletingOwnershipInfo.id, deletingOwnershipInfo.ownedFrom, i
            );
            try {
                await deletePerson({
                    id: '',
                    project: { typeOf: chevre.factory.organizationType.Project, id: DISCONTINUE_PEOPLE_PROJECT },
                    name: chevre.factory.taskName.DeletePerson,
                    status: chevre.factory.taskStatus.Ready,
                    runsAt,
                    remainingNumberOfTries: 10,
                    numberOfTried: 0,
                    data: {
                        id: personId,
                        agent: {
                            id: DISCONTINUE_PEOPLE_PROJECT,
                            typeOf: chevre.factory.organizationType.Project,
                            name: 'example'
                        },
                        physically: true,
                        userPoolId,
                        migrate: false,
                        useUsernameAsGMOMemberId: true,
                        paymentMethodType4creditCard: 'CreditCard',
                        executeBackground: true
                    }
                })(
                    {
                        connection: mongoose.connection,
                        settings: new chevre.settings.Settings({
                            abortedTasksWithoutReport: [],
                            numTryConfirmReserveTransaction: 10,
                            deliverOrderLimit: 1,
                            coa: {
                                timeout: 20000
                            },
                            gmo: {
                                timeout: 5000,
                                timeoutBackground: 5000,
                                useFetch: true
                            },
                            movieticketReserve: {
                                timeout: 1000,
                                timeoutCheck: 1000,
                                minIntervalBetweenPayAndRefund: 1000,
                                credentialsExpireInSeconds: 1000
                            },
                            useExperimentalFeature: false
                        }),
                        credentials: <any>{}
                    },
                    {
                        executeById: false,
                        executeByName: true
                    }
                );
                console.log(
                    'deleted',
                    personId, deletingOwnershipInfo.project.id, deletingOwnershipInfo.id, deletingOwnershipInfo.ownedFrom, i
                );
            } catch (error) {
                // no op
            }
        });

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

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