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

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 actionRepo = await chevre.repository.Action.createInstance(mongoose.connection);

    const cursor = actionRepo.getCursor(
        {
            typeOf: { $eq: chevre.factory.actionType.CheckAction },
            'object.typeOf': { $eq: chevre.factory.service.paymentService.PaymentServiceType.MovieTicket },
            // 'project.id': { $eq: project.id },
            startDate: {
                $gte: moment()
                    // tslint:disable-next-line:no-magic-numbers
                    .add(-90, 'days')
                    .toDate()
                // $lte: moment('2023-08-01T21:20:43.133Z')
                //     .toDate()
            }
        },
        {
            startDate: 1,
            object: 1,
            project: 1,
            instrument: 1,
            purpose: 1
        }
    );
    console.log('actions found');

    let i = 0;
    let updateCount = 0;
    const actions: Pick<
        chevre.factory.action.check.paymentMethod.movieTicket.IAction,
        'startDate' | 'object' | 'project' | 'instrument' | 'id' | 'purpose'
    >[] = [];
    await cursor.eachAsync(async (doc) => {
        i += 1;
        const action: Pick<
            chevre.factory.action.check.paymentMethod.movieTicket.IAction,
            'startDate' | 'object' | 'project' | 'instrument' | 'id' | 'purpose'
        > = doc.toObject();

        const alreadyMigrated = typeof action.purpose?.id === 'string'
            && action.purpose?.id.length > 0;

        if (alreadyMigrated) {
            console.log('already exist.', action.project.id, action.id, action.purpose?.typeOf, action.purpose?.id, action.startDate, i);
        } else {
            console.log('updating...', action.project.id, action.id, action.purpose?.typeOf, action.purpose?.id, action.startDate, i);
            updateCount += 1;
            actions.push(action);
            console.log('updated.', action.project.id, action.id, action.purpose?.typeOf, action.purpose?.id, action.startDate, i);
        }
    });

    console.log('invalidAction:', actions);
    console.log(i, 'actions checked');
    console.log(updateCount, 'actions updated');
}

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