// tslint:disable:no-console
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 eventRepo = await chevre.repository.Event.createInstance(mongoose.connection);

    const cursor = eventRepo.getCursor(
        {
            'project.id': {
                $nin: [
                    'sskts-test',
                    'sskts-production'
                ]
            },
            startDate: { $gte: new Date('2025-04-10T00:00:00Z') }
        },
        {
            offers: 1,
            project: 1,
            typeOf: 1,
            startDate: 1,
            location: 1,
            aggregateReservation: 1
        }
    );
    console.log('docs found');

    let i = 0;
    let hasNoSeatsCount = 0;
    let tooManyReservationCount = 0;
    let maxReservationCount = 0;
    const targetIds: string[] = [];
    const projectIds: string[] = [];
    await cursor.eachAsync(async (doc) => {
        i += 1;
        const event: Pick<
            chevre.factory.event.screeningEvent.IEvent, 'id' | 'offers' | 'startDate' | 'typeOf' | 'location' | 'project' | 'aggregateReservation'
        > = doc.toObject();

        // const hasMax = typeof event.location.maximumAttendeeCapacity === 'number';
        const hasSeats = event.offers.itemOffered.serviceOutput?.reservedTicket?.ticketedSeat?.typeOf === chevre.factory.placeType.Seat;
        if (!hasSeats) {
            hasNoSeatsCount += 1;
            targetIds.push(event.id);
            projectIds.push(event.project.id);
            console.log(
                'hasNoSeatsCount:', hasNoSeatsCount,
                event.id, event.project.id, event.startDate, i);
        } else {
            console.log(
                'no', hasNoSeatsCount,
                event.id, event.project.id, event.startDate, i);
        }

        const reservationCount = event.aggregateReservation?.reservationCount;
        if (typeof reservationCount === 'number') {
            maxReservationCount = Math.max(reservationCount, maxReservationCount);
        }
        const tooManyReservation = typeof event.aggregateReservation?.reservationCount === 'number'
            // tslint:disable-next-line:no-magic-numbers
            && event.aggregateReservation?.reservationCount > 2000;
        if (tooManyReservation) {
            tooManyReservationCount += 1;
            console.log(
                'tooManyReservationCount:', tooManyReservationCount,
                event.id, event.project.id, event.startDate, i);
        }

    });

    console.log(targetIds);
    console.log(i, 'docs checked');
    console.log(hasNoSeatsCount, 'docs hasNoSeatsCount');
    console.log('projectIds:', [...new Set(projectIds)]);
    console.log('maxReservationCount:', maxReservationCount);
}

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