// 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) };

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

    const actionRepo = await chevre.repository.Action.createInstance(mongoose.connection);
    const startLte = moment()
        .add(-1, 'week')
        .toDate();

    const cursor = actionRepo.getCursor(
        {
            // 'project.id': { $ne: EXCLUDED_PROJECT_ID },
            actionStatus: { $eq: chevre.factory.actionStatusType.ActiveActionStatus },
            startDate: { $lt: startLte }
        },
        {
            _id: 1,
            startDate: 1,
            typeOf: 1,
            project: 1
        }
    );
    console.log('actions found');

    let i = 0;
    // let updateCount = 0;
    await cursor.eachAsync(async (doc) => {
        i += 1;
        // if (i > 1) {
        //     return;
        // }

        console.log('updating...', doc.project.id, doc.typeOf, doc.id, doc.startDate);
        const result = await actionRepo.giveUpStartDatePassedCertainPeriod({
            id: { $eq: doc.id },
            startDate: { $lt: startLte },
            error: new chevre.factory.errors.GatewayTimeout('unexpected timeout')
        });
        console.log('updated', doc.project.id, doc.typeOf, doc.id, doc.startDate, result);
    });

    console.log(i, 'actions checked');
    // console.log(updateCount, 'events updated');
}

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