import { Injectable, Logger } from "@nestjs/common";
import { OnEvent } from "@nestjs/event-emitter";
import { InjectModel } from "@nestjs/mongoose";
import mongoose from "mongoose";
import { CronSyncService } from "src/AnalyticsReport/CronSyncService.service";
import { CurrentStage } from "../enum/CurrentStage.enum";
import { recordTypeEnum } from "src/models/AnalyticsReport.schema";
import { AppleAccount } from "src/models/AppleAccount.schema";
import { LoggerService } from "src/utils/logger.service";

@Injectable()
export class ReportEvent {
    private readonly logger = new Logger(ReportEvent.name);

    constructor(
        @InjectModel("AppleAccount") private AppleAccountRepo: mongoose.Model<AppleAccount>,
        private cronSyncService: CronSyncService,
        private loggerService: LoggerService
    ) { }

    @OnEvent('sync.Report', { async: true })
    async sentReport(fromDate, toDate, record) {

        try {
            const salesStatus = await this.cronSyncService.doSyncReportInBatch(fromDate, toDate, recordTypeEnum.SALES, record)
            console.log('salesStatus>>>>>>>>>', salesStatus)
            // this.logger.debug(`Sales sync report status: ${salesStatus}`);

            const downloadStatus = await this.cronSyncService.doSyncReportInBatch(fromDate, toDate, recordTypeEnum.DOWNLOAD, record)
            console.log('downloadStatus>>>>>>>', downloadStatus);
            // this.logger.debug(`Downloads sync report status: ${downloadStatus}`);

            await this.AppleAccountRepo.updateMany(
                {},
                { $set: { InitialSyncStatus: CurrentStage.COMPLETED } }
            );
            this.loggerService.log(`Sync report processed successfully for record` + " " + `${record._id}`);

        } catch (error) {
            // this.logger.error(`Error occurred in sentReport: ${error.message}`, error.stack);
            console.log(error, 'error');
        }
    }
}
